How do I replace multiple lines with single word in file(inplace replace)?
This can be done very easily in perl
:
$ perl -i -p0e 's/START.*?END/SINGLEWORD/s' file
$ cat file
My block of line starts from here
SINGLEWORD
and end to here for example.
Explanation
-0
sets the line separator to null
-p
apply the script given by -e
to each line and print that line
The regexp modifier:
/s
Treat string as single line. That is, change.
to match any character whatsoever, even a newline, which normally it would not match.
Why the ?
:
- By default, a quantified subpattern is "greedy", that is, it will match as many times as possible (given a particular starting location) while still allowing the rest of the pattern to match. If you want it to match the minimum number of times possible, follow the quantifier with a
?
.
I was wondering if this is possible without perl
, python
and others. And I found this solution using sed
:
$ sed ':a;N;$!ba;s/START.*END/SINGLEWORD/g' filename
Explanation:
- :a create a label 'a'
- N append the next line to the pattern space
- $! if not the last line, ba branch (go to) label 'a'
- s substitute,
/START.*END/
bySINGLEWORD
,/g global match (as many times as it can)
It was found here.