Bash: Update a variable within a file

前端 未结 3 1808
滥情空心
滥情空心 2021-01-26 03:41

I know this is a simple answer and I could probably keep digging around on Google before I stroll across the answer. But I am on a tight schedule and I was hoping for an easy re

相关标签:
3条回答
  • 2021-01-26 03:54

    You can make use of something like this, which lets you define exactly what values you want to add in the file:

    $ bootproto="static"
    $ sed -r "s/(BOOTPROTO\s*=\s*).*/\1$bootproto/" file
    ONBOOT=no
    BOOTPROTO=static
    

    And to make the two of them together:

    $ onboot="yes"
    $ bootproto="static"
    $ sed -r -e "s/(ONBOOT\s*=\s*).*/\1$onboot/" -e "s/(BOOTPROTO\s*=\s*).*/\1$bootproto/" file
    ONBOOT=yes
    BOOTPROTO=static
    

    Explanation

    • (BOOTPROTO\s*=\s*).* catches a group of text containing BOOTPROTO + any_number_of_spaces + = + any_number_of_spaces. Then, matches the rest of the text, that we want to remove. \1$var prints it back together with the given variable.
    • \s* keeps the current spaces as they were and then replaces the same line changing the current text with the bash variable $bootproto.
    • -r is used to catch groups with () instead of \( and \).

    To make it edit in place, use sed -i.bak. This will create a backup of the file, file.bak, and the file will be updated with the new content.

    All together:

    sed -ir -e "s/(ONBOOT\s*=\s*).*/\1$onboot/" -e "s/(BOOTPROTO\s*=\s*).*/\1$bootproto/" file
    
    0 讨论(0)
  • 2021-01-26 04:00

    The similar as the sed solutons with perl

    perl -i.bak -pe 's/(ONBOOT)=no/$1=yes/;s/(BOOTPROTO)=dhcp/$1=static/' files....
    
    0 讨论(0)
  • 2021-01-26 04:00
    sed -i -e '/^ONBOOT=/s|.*|ONBOOT=yes|; /^BOOTPROTO=/s|.*|BOOTPROTO=static|' file
    

    Also try:

    sed -i -re 's|^(ONBOOT=).*|\1yes|; s|^(BOOTPROTO=).*|\1static|' file
    

    Or

    sed -i -e 's|^\(ONBOOT=\).*|\1yes|; s|^\(BOOTPROTO=\).*|\1static|' file
    
    0 讨论(0)
提交回复
热议问题