Найти конкретный текст в файле и обернуть другим текстом - PullRequest
1 голос
/ 27 февраля 2012

Я ищу лучший способ найти определенный текст в файле и обернуть другой текст вокруг него из командной строки Linux.

Так, например, файл может содержать следующее:

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

Итак, в приведенном выше примере я хочу найти текст между anchor-start и anchor-end, а затем обернуть этот текст так, чтобы я получил:

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

Я должен также отметить, чтоЯ ищу решение, согласно которому, если сразу за anchor-start следует wrapping-start (т. Е. Обертка уже произошла), его не следует дублировать.

Ответы [ 2 ]

2 голосов
/ 27 февраля 2012

Это может работать для вас:

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
0 голосов
/ 27 февраля 2012
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
...