Vasyl Stepulo
Vasyl Stepulo

Reputation: 1603

sed insert newline after match

I have a variable with following content:

k1065-betfirst-4ccc6a2cf196 (192.168.255.46) is off-line k1164-betfirst-4ccc6a8ff0be (192.168.255.54) is off-line K1165-BetFirst-4ccc6a2cf343 (192.168.255.26) is off-line K1185-BetFirst-4ccc6aba7af7 (192.168.255.18) is off-line k1331-betfirst-448a5bb71eb8 (192.168.255.38) is off-line

I need to insert after "line" linebreak. In order to do this, I use sed:

echo -e $mailbody | sed 's/line/\n&/g' | tee -a hosts2.txt

But it insert newline before "line":

 k1065-betfirst-4ccc6a2cf196 (192.168.255.46) is off-
line k1164-betfirst-4ccc6a8ff0be (192.168.255.54) is off-
line K1165-BetFirst-4ccc6a2cf343 (192.168.255.26) is off-
line K1185-BetFirst-4ccc6aba7af7 (192.168.255.18) is off-
line k1331-betfirst-448a5bb71eb8 (192.168.255.38) is off-
line

Can anyone give me a hint, how to rewrite sed, to write newline after "line"?

Upvotes: 1

Views: 603

Answers (3)

Katrin Leinweber
Katrin Leinweber

Reputation: 1548

In BSD/macOS sed, a literal newline with \-escape must be used:

's/line */\
/g'

Upvotes: 0

Paul Hodges
Paul Hodges

Reputation: 15246

c.f. this resource for lots of good examples. e.g.:

# insert a blank line below every line which matches "regex"
sed '/regex/G'

Upvotes: 0

choroba
choroba

Reputation: 241748

Try swapping the & and \n. Also, you might need to remove the space after line:

's/line */&\n/g'

Upvotes: 1

Related Questions