Sriharsha Kalluru
Sriharsha Kalluru

Reputation: 1823

Add two consecutive lines in sed

I would like to add two lines after the first string search. I am using:

$ cat file1
HAI
BYE
HAI
ONE
TWO

$ VAR=`cat -n file1 |grep -w HAI |head -1 |awk '{print $1}'`
$ sed "$VAR a\
LINE ONE \
LINE TWO
" file1

It is giving the following output.

HAI
LINE ONE LINE TWO
BYE
HAI
ONE
TWO

But I want the output to be:

HAI
LINE ONE 
LINE TWO
BYE
HAI
ONE
TWO

How can I achieve this? I tried to keep the \n but it is giving errors.

Upvotes: 2

Views: 3898

Answers (3)

anubhava
anubhava

Reputation: 785088

Replace your sed command with this:

sed $VAR' a\
LINE ONE\
LINE TWO
' file1

btw your earlier grep, awk can also be reduced to this:

VAR=$(awk '$1 == "HAI" && NR==1{print NR}' file1)

Much Better is to get full answer in single awk command like this:

awk '{if ($1=="HAI" && done!=1) {done=1; printf("%s\nLINE ONE\nLINE TWO\n", $0);} \
      else print $0}' file1

OUTPUT:

HAI
LINE ONE
LINE TWO
BYE
HAI
ONE
TWO

Upvotes: 4

potong
potong

Reputation: 58381

This might work for you (GUN sed):

sed '0,/HAI/a\LINE ONE\nLINE TWO' file

or this (any sed):

sed 'x;/./{x;b};x;/HAI/!b;h;a\LINE ONE\nLINE TWO' file

Upvotes: 0

kev
kev

Reputation: 161664

$ sed '/HAI/{s/.*/&\nLINE ONE\nLINE TWO/;:a;n;ba}' file1
HAI
LINE ONE
LINE TWO
BYE
HAI
ONE
TWO

Explanation:

  • /HAI/ search this pattern
  • s/.*/&\nLINE ONE\nLINE TWO/ append two lines
  • :a define a label(a)
  • n read next line
  • ba jump to label(a)

You can use the a command instead of s:

$ sed '
> /HAI/{
> a\
> LINE ONE\
> LINE TWO
> :a
> n
> ba
> }' file1

Upvotes: 2

Related Questions