1

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?

1
  • 2
    It is possible to solve the problem with sed or awk. What have you tried so far? Commented Jun 1, 2016 at 6:30

3 Answers 3

4
$ 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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! curly braces were missing from my command. It is working now
1

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

2 Comments

I don't think "do_not_modify" is actually present in the input file.
Yes may be OP would have wanted awk 'NR>1 && !/-string-exists$/{$0 = $0 "-string-exists"} 1' file
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.