Sed - add to next line using command line

I want to add "dddd" to the next line whenever I encounter "=" in a text file.

This command

sed -i '/=/s|$| dddd|' *.krn

close to what I'm looking for as it joins the current line where "=" is. How can I add to the next line?

+3


source to share


4 answers


Use append, see here:

eg:.

$ echo $'abc\ndef\ne=f\nqqq'
abc
def
e=f
qqq
$ echo $'abc\ndef\ne=f\nqqq'|sed '/=/adddd'
abc
def
e=f
dddd
qqq

      



Edited for clarification as per comment from @ je4d- if you want to add to what's on the next line, you can use this:

$ echo $'abc\ndef\ne=f\nqqq\nyyy'
abc
def
e=f
qqq
yyy
$ echo $'abc\ndef\ne=f\nqqq\nyyy'|sed '/=/{n;s/$/ dddd/}'
abc
def
e=f
qqq dddd
yyy

      

See here for a great collection of cheatsheet for more information if you want:

+3


source


So, to repeat the question, when you settle for one line, you want to add a line to the next line --- an already existing line, rather than adding a new line after it with new data.

I think this will work for you:

sed '/=/ { N; s/$/ ddd/ }'

      

Let's say you have a file like:



=
hello
world
=
foo
bar
=

      

Then processing that command on it will give:

=
hello ddd
world
=
foo ddd
bar
=

      

In this case, the command is used N

. This is read on the "next" line of input. Then the commands will be applied to the next line.

+3


source


I'm not a saga guru, but I can do what you want with awk:

'{PREV=MATCH; MATCH="no"}
 /=/{MATCH="yes"} 
 PREV=="yes"{print $0 " dddd"}
 PREV!="yes"{print}'

      

Demo:

$ echo -e 'foo\nba=r\nfoo\n=bar\nfoo\nfoo\nb=ar\nx' 
foo
ba=r
foo
=bar
foo
foo
b=ar
x

$ echo -e 'foo\nba=r\nfoo\n=bar\nfoo\nfoo\nb=ar\nx' | awk '{APPEND=LAST; LAST="no"} /=/{LAST="yes"} APPEND=="yes"{print $0 " dddd"} APPEND!="yes"{print}'
foo
ba=r
foo dddd
=bar
foo dddd
foo
b=ar
x dddd

      

+1


source


This might work for you:

echo -e "=\nx " | sed '/=/{$q;N;s/$/dddd/}'
=
x dddd

      

0


source







All Articles