Marty Wallace
Marty Wallace

Reputation: 35776

Find specific text in file and wrap in with other text

I am looking for the best method to find specific text within a file and wrap other text around it from the Linux command line.

So for example the file may contain the following:

This
is
a
test.
anchor-start
text to wrap will is in here
anchor-end

So in the above example I want to find the text in between anchor-start and anchor-end and then wrap that text so that I end up with:

This
is
a
test.
anchor-start
wrapping-start
text to wrap will is in here
wrapping-end
anchor-end

I should also note that I am looking for a solution whereby if anchor-start is immediately followed by wrapping-start (i.e. the wrapping has already occurred) then it should not be duplicated.

Upvotes: 1

Views: 238

Answers (2)

Vijay
Vijay

Reputation: 67291

pearl.319> cat temp.pl
This 
is a 
test. 
anchor-start
text to wrap will 
is in here 
anchor-end
pearl.320> perl -p -e 's/anchor-start/anchor-start\nwrap-start/g;s/anchor-end/wrap-end\nanchor-end/g' temp.pl
This 
is a 
test. 
anchor-start
wrap-start
text to wrap will 
is in here 
wrap-end
anchor-end

Upvotes: 0

potong
potong

Reputation: 58528

This might work for you:

sed '/anchor-start/,/anchor-end/{/anchor-start/{h;d};H;/anchor-end/{x;/wrapping-start/b;s/\n.*\n/\nwrapping-start&wrapping-end\n/p};d}' file
This
is
a
test.
anchor-start
wrapping-start
text to wrap will is in here
wrapping-end
anchor-end

Upvotes: 2

Related Questions