Manisha Manisha - 6 months ago 26
Bash Question

Replace a string with another substring using sed in shell script

For every line except the first line in my file,I want to check if a string already exists . If it does, then do nothing. Otherwise, append the string to the line

For ex - there are foll 3 lines in my file

line1 : do_not_modify

line2-string-exists

line3


I want to append
-string-exists
to only those lines in the file which does not have that string appended to them(Ignore the first line)

the output should be -

line1 : do_not_modify

line2-string-exists

line3-string-exists


Please tell me How will I do it using
sed
? Or is it possible to do with
awk
?

Answer
$ cat data
line1 : do_not_modify
line2-string-exists
line3

$ sed '1!{/-string-exists/! s/$/-string-exists/}' data
line1 : do_not_modify
line2-string-exists
line3-string-exists

or using awk:

$ awk '{if(NR!=1 && ! /-string-exists/) {printf $0; printf "-string-exists\n"} else {print}}' data
line1 : do_not_modify
line2-string-exists
line3-string-exists