If no sed pattern echo >> newline

I use sed to replace strings in conf:

sed -i.bak 's/^option.*/option newparam/' somefile.conf

If my options string does not exist in some file, how can I tell sed insert it or return false?

Finally, I ended up with:

sed -i.bak "s/^#$STR.*\|^# $STR.*\|^$STR.*/$OPT/" $FILE && grep -q "^$OPT" $FILE || echo "$OPT" >> $FILE

+4
source share
3 answers

Delete line (s) starting with option , add ( a ) option newparam to last line ( $ ) of file

 sed -i.bak '/^option/d; $ a\option newparam' somefile.conf 

Note: since you said you want to insert a new line if the option line does not exist, I assumed that where the new line is located does not matter.

+4
source

Use grep to check if the first line exists if it does not add it to the end of the file using the double pipe operator || . The operation will be short if the first command returns true, and therefore the second command will only be executed when the first failure.

grep -q '^option.*' file.txt || echo 'option newparam' >> file.txt

The -q suppresses grep output, and the || only executes the echo command if the grep fails, that is, if $? not 0 . A simple example:

 $ cat file.txt line 1 line 2 line 3 $ grep -q 'line 4' file.txt || echo 'line not in file' line not in file 

Special variable $? contains the exit value from the previous command.

 $ grep -q 'line 4' file.txt $ echo $? 1 $ grep -q 'line 3' file.txt $ echo $? 0 
+2
source

You can do this in GNU sed, keeping the order of options:

 /^otheroption.*/ { s//otheroption newparam/ # Insert newparam h # and remember it in HS } $ { x # Check if option /^otheroption/! { # was replaced, x # if not append it s/$/\notheroption newparam/ # to the last line } } 

All in one line:

 sed '/^option.*/ { s//option newparam/; h; }; $ { x; /^option/! { x; s/$/\noption newparam/; }; }' somefile.conf 
+1
source

Source: https://habr.com/ru/post/1445162/


All Articles