Manisha
Manisha

Reputation: 815

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?

Upvotes: 1

Views: 271

Answers (3)

riteshtch
riteshtch

Reputation: 8769

$ 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 "%s%s", $0, "-string-exists\n"} else {print}}' data
line1 : do_not_modify
line2-string-exists
line3-string-exists

Upvotes: 4

Ed Morton
Ed Morton

Reputation: 203502

Assuming the string doesn't contain any RE metacharacters:

$ awk 'BEGIN{s="-string-exists"} (NR>1) && ($0!~s"$"){$0=$0 s} 1' file
line1 : do_not_modify
line2-string-exists
line3-string-exists

Upvotes: 0

anubhava
anubhava

Reputation: 785146

You can use this sed command:

sed -E '/(do_not_modify|-string-exists)$/!s/$/-string-exists/' file

line1 : do_not_modify
line2-string-exists
line3-string-exists

Or using awk:

awk '!/(do_not_modify|-string-exists)$/{$0 = $0 "-string-exists"} 1' file

Upvotes: 1

Related Questions