Tingrammer
Tingrammer

Reputation: 251

appending a line after there is match for 2 pattern in Unix shell scripting

I have a file like

nithin shetty
sachin shetty
pavan shetty

In this file i want to append "HELLO THIS IS ME",next line to the pattern "shetty". But the condition is that if the line matches for "nithin" , then don't append the line. I know how to append a line after a pattern match,

sed '/shetty/a\
  HELLO THIS IS ME
' filename`

But in this i don't want a line containing nithin. Output should be like this:

nithin shetty
sachin shetty
  HELLO THIS IS ME
pavan shetty
  HELLO THIS IS ME

Is it possible??

Upvotes: 2

Views: 1271

Answers (3)

Thor
Thor

Reputation: 47229

Here's one way to do it with awk:

awk '!/nithin/ && /shetty/ { $0 = $0 "\n  HELLO THIS IS ME" } 1' infile

Output:

nithin shetty
sachin shetty
  HELLO THIS IS ME
pavan shetty
  HELLO THIS IS ME

Upvotes: 0

ikegami
ikegami

Reputation: 386676

Sorry, I don't know sed, but I do know Perl.

perl -nE'print; say "HELLO THIS IS ME" if /shetty/ && !/nithin/'

or

perl -pe'$_ .= "HELLO THIS IS ME\n" if /shetty/ && !/nithin/'

Like with sed,

  • Lines will be read from the named file(s) or from stdin if no files are named.
  • Output will be sent to stdout.
  • You can use -i for in-place editing.

Upvotes: 2

devnull
devnull

Reputation: 123658

A sed solution would be of the form:

sed '/nithin/b; /shetty/a\ HELLO THIS IS ME' filename

b would cause sed to branch to the end of the script in the absence of a label.

Upvotes: 3

Related Questions