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.

1
  • 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... Commented Oct 25, 2016 at 22:31

4 Answers 4

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
  • 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 Commented Oct 26, 2016 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.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.