Reputation: 213
I wish to append " dddd" to the next line whenever I encounter "=" in a textfile.
This command
sed -i '/=/s|$| dddd|' *.krn
is close to what I am looking for as it appends to the current line where "=" is. How can I append to the next line instead?
Upvotes: 3
Views: 4622
Reputation: 58381
This might work for you:
echo -e "=\nx " | sed '/=/{$q;N;s/$/dddd/}'
=
x dddd
Upvotes: 0
Reputation: 28598
Use append, see here:
E.g.:
$ 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 to clarify as per comment from @je4d- if you want to append to what is present in 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 sed cheatsheet for more info if you want:
Upvotes: 3
Reputation: 5919
So to reiterate the question, when you match on one line, you want to append a string to the next line---a line that already exists, rather than adding a new line after it with the new data.
I think this will work for you:
sed '/=/ { N; s/$/ ddd/ }'
Say you have a file like:
=
hello
world
=
foo
bar
=
Then processing this command on it will yield:
=
hello ddd
world
=
foo ddd
bar
=
The trick here is using the N
command first. This reads in the "next" line of input. Commands following it will be applied to the next line.
Upvotes: 3
Reputation: 7838
I'm not a sed 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
Upvotes: 1