sed匹配后插入换行符

时间:2018-10-22 14:18:55

标签: bash sed

我有一个变量,其内容如下:

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

我需要在“换行”后插入。为此,我使用sed:

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

但是它在“行”之前插入换行符:

 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

谁能给我一个提示,如何重写sed,在“行”之后写换行符?

3 个答案:

答案 0 :(得分:0)

尝试交换&\n。另外,您可能需要删除line之后的空格:

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

答案 1 :(得分:0)

c.f。 this resource中有很多很好的例子。例如:

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

答案 2 :(得分:0)

在 BSD/macOS sed 中,必须使用带有 \-escape 的文字换行符:

's/line */\
/g'