How to add text after last pattern match using ed

2020-03-31 08:16发布

问题:

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).



标签: linux bash ed