Reputation: 53
I'm using sed
to replace lines in conf's:
sed -i.bak 's/^option.*/option newparam/' somefile.conf
If my option line does not exist in somefile, how do I tell sed
to 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
Upvotes: 4
Views: 592
Reputation: 47229
You could do it like this in GNU sed, preserving option order:
/^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 on one line:
sed '/^option.*/ { s//option newparam/; h; }; $ { x; /^option/! { x; s/$/\noption newparam/; }; }' somefile.conf
Upvotes: 1
Reputation: 8408
Delete line(s) that begins with option
, append (a
) option newparam
to last line ($
) of the file
sed -i.bak '/^option/d; $ a\option newparam' somefile.conf
Note: since you said you want to insert the new line if option
line doesn't exist, I assumed that where the new line is located does not matter.
Upvotes: 4
Reputation: 85883
Use grep to check if the line exist first if it doesn't append it to the end of the file using the double pipe operator ||
. The operation will be short circuited if the first command returns true and therefor the second command is only ever executed if the first fails.
grep -q '^option.*' file.txt || echo 'option newparam' >> file.txt
The -q
option suppresses the output of grep and the ||
operator will only execute the echo
command if the grep
command fails, that is if $?
is 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
The 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
Upvotes: 2