1

I have a file that I want to find a key word in and enter text 2 lines down.

For example lets say the file i have contains the following words

the
cow
goes
moo

I want to be able to find the word "cow" and enter the text "yay" into the file 2 lines below the word cow.

the
cow
goes
moo
yay

I believe this would be done with sed but cannot get it to work.

Any help is greatly appreciated.

  • Note that none of the answers below will work as expected if cow occurs on more than one line and any two matching lines aren't separated by at least two non-matching lines... – don_crissti Oct 25 '16 at 22:31
2
$ cat ip.txt 
the
cow
goes
moo

$ sed '/cow/{N;N; s/$/\nyay/}' ip.txt 
the
cow
goes
moo
yay
  • N;N; get next two lines
  • s/$/\nyay/ add another line
  • 1
    Thank Sundeep. I was able to use your provided command and add the -i to sed to accomplish what i need to do. Thanks again – user4901146 Oct 26 '16 at 13:08
1

With awk:

awk '/cow/ {print; getline; print; getline; print; print "yay"; next}; 1'
  • /cow/ matches cow in the record, and then {print; getline; print; getline; print; print "yay"; next} prints the line, getline gets us the next line, that is printed too, same for the next, and then yay is printed, then goes to the next line (next)

  • 1 (true) will print the rest of the lines as default action

Caveat:

  • If there are less that two lines between the pattern to search and EOF, then the last line starting from pattern will be repeated to make two lines in between

Example:

% cat file.txt
the
cow
goes
moo

% awk '/cow/ {print; getline; print; getline; print; print "yay"; next}; 1' file.txt
the
cow
goes
moo
yay
0

Other sed

sed '/cow/! b;n;n;a\yay' file.txt

Other awk

awk '{print;this--};/cow/{this=2}! this{print "yay"}' file.txt
0

With ed

ed file << EOF
/cow/+2a
yay
.
,p
q
EOF

to print the modified output; or

ed file << EOF
/cow/+2a
yay
.
wq
EOF

or (as a bash one-liner)

printf '%b\n' '/cow/+2a' 'yay\n.' 'wq' | ed file

to write the changes in place.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.