Home > Back-end >  sed match string in file and replace line that include value after separator
sed match string in file and replace line that include value after separator

Time:07-26

in /etc/barman.conf configuration file

we have the following line

retention_policy = RECOVERY WINDOW OF 7 days

in our bash script we want to add sed command or maybe Perl one liners , that will change the integer value between the words "OF" and "days"

number 7 in above example - could be any integer number and should be replace according to new value - $NUM_OF_DAY

we tries with following option , that replaced the value after “=” separator but without success

NUM_OF_DAYS=23

sed '/retention_policy/!b; n; s/RECOVERY WINDOW OF [0-9]  days/RECOVERY WINDOW OF $NUM_OF_DAYS days/g'  /etc/barman.conf

or maybe the best option is completely delete the words/value after “=” separator and re-set the new line - RECOVERY WINDOW OF $NUM_OF_DAY days

CodePudding user response:

Using sed

$ num_of_days=23
$ sed -E "/^(retention_policy[^[:digit:]]*)[[:digit:]] /s//\1$num_of_days/" /etc/barman.conf
retention_policy = RECOVERY WINDOW OF 23 days

CodePudding user response:

I am not sure how strict your input file line syntax is, but if ^retention_policy is used for line matching, and number is between OF and days strings, you may try something like:

$ NUM_OF_DAYS=42
$ sed -E "/^retention_policy/ s/(.*OF )[0-9] ( days.*)$/\1$NUM_OF_DAYS\2/" /tmp/foo.conf

or the simpler alternative :

$ NUM_OF_DAYS=42
$ sed -E "s/(^retention.*OF )[0-9] ( days.*)$/\1$NUM_OF_DAYS\2/" /tmp/foo.conf

With the output:

$ cat /tmp/foo.conf
retention_policy = no match
retention_policy = RECOVERY WINDOW OF 7 days
no match
$ sed -E "/^retention_policy/ s/(.*OF )[0-9] ( days.*)$/\1$NUM_OF_DAYS\2/" /tmp/foo.conf
retention_policy = no match
retention_policy = RECOVERY WINDOW OF 42 days
no match
$ sed -E "s/(^retention.*OF )[0-9] ( days.*)$/\1$NUM_OF_DAYS\2/" /tmp/foo.conf
retention_policy = no match
retention_policy = RECOVERY WINDOW OF 42 days
no match
  • Related