Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell command for in-place multi-line regex replace

Tags:

regex

ruby

With single line regex you can use -p and $_.sub!:

$ cat file.txt
<a
a>
c
$ ruby -i -pe '$_.sub!("a", "b")' file.txt
$ cat file.txt
<b
b>
c

Is there any short way to replace multi-line patterns? I currently use something like this:

$ ruby -i -e 'print *readlines.join.sub(/<.*>/m, "d")' file.txt
$ cat file.txt
d
c
like image 506
Lri Avatar asked Nov 28 '25 05:11

Lri


1 Answers

Using gets(nil) saves you a whopping 6 characters :)

ruby -i -e 'print gets(nil).sub(/<.*>/m, "d")' file.txt

From the gets docs:

The optional argument specifies the record separator. The separator is included with the contents of each record. A separator of nil reads the entire contents. [...]

like image 200
exbinary Avatar answered Nov 30 '25 18:11

exbinary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!