Bash: Update a variable within a file

前端 未结 3 1815
滥情空心
滥情空心 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
    

提交回复
热议问题