How to add text after last pattern match using ed

♀尐吖头ヾ 提交于 2019-12-01 12:14:38

问题


This is how I am adding text before first pattern, I want to add after last pattern

FILE_NAME="folder/myfile.c++"
STR_TO_ADD="string that i want to add"
PATTERN="banana"
ed $FILE_NAME 2>NULL 1>NULL<<EOF
/^$PATTERN
-1
a
$STR_TO_ADD
.
wq
EOF

file

banana
apple
banana
one
two
three

Expected output

banana
apple
banana
string that i want to add
one
two
three

回答1:


Go to last line of file and search pattern in backward direction.

FILE_NAME="folder/myfile.c++"
STR_TO_ADD="string that i want to add"
PATTERN="banana"
ed $FILE_NAME 2>NULL 1>NULL<<EOF
$
?^$PATTERN
a
$STR_TO_ADD
.
wq
EOF

$ last line of file.
?^$PATTERN search pattern in backward direction from current line.




回答2:


The solution by user0 is close, but if the last match falls on the last line of the file, it will find the previous one. Instead, go to the first line and search backward:

1
?^$PATTERN
a
$STR_TO_ADD
.

I just posted this on my @ed1conf account a couple days ago so it's fresh in my mind.

Additionally, if you're trying to add before the text (the example you already have), it will fail if the first match is on the first line because the "-1" goes before the start of the file. Instead, use the "i" command to insert the text rather than append it:

$
/^$PATTERN
i
$STR_TO_ADD
.

You might also need to ensure that "$STR_TO_ADD" doesn't contain any lines containing a single period or the variable-expansion will prematurely terminate the insertion (or appending).



来源:https://stackoverflow.com/questions/56932739/how-to-add-text-after-last-pattern-mach-using-ed

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!