Reputation: 324455
I have a file with lines like
something
-----------
where there's a leading and trailing space after something
. I want to replace it with
other
-------
and preserve the leading and trailing space. How?
Upvotes: 0
Views: 184
Reputation: 203502
sed is for simple substitutions on individual lines, that is all, for anything else you should be using awk:
$ awk 'n{$0=substr($0,1,n); n=0} {sub(/^ something $/," other "); n=length()}1' file
other
-------
That will work with any awk in any shell on any UNIX box.
Upvotes: 1
Reputation: 58400
This might work for you (GNU sed):
sed -i '/^ something $/{:a;N;/^--*$/M!ba;s/something/other/}' file
Gather up lines between the start and end markers, then replace the required string with the alternative.
N.B. Uses the M
flag to make an exact match within multiple lines.
Upvotes: 1
Reputation: 324455
sed
can match multiple lines with a comma separated set of regexps. And substitute everything in the range with the c
command. To get the c
command not to ignore leading white space, use a backslash after it. e.g.
sed -i.original '/^ something $/,/-----------$/c\ other \n-------' input-filename
Upvotes: 0