How to use Ruby's command line in-place-edit mode to remove lines from a text file

700 views Asked by At

I've been a long time perl user, and in perl you can easily remove lines from text files like this:

perl -pi -e 'undef $_ if m/some-condition/' file.txt

I'm trying to move my scripting to Ruby, which also does in-place-edit, so I wrote this:

ruby -pi -e '$_ = nil if $_ =~ /some-condition/' file.text

but that instead nullified the entire file. I then tried

ruby -pi -e 'nil if $_ =~ /some-condition/' file.text

but that didn't do anything.

Any ideas?

1

There are 1 answers

0
Amadan On BEST ANSWER
ruby -pi -e '$_ = nil if $_ =~ /some-condition/' file.text

should be correct. If it doesn't work, the problem is in some-condition. To demonstrate,

echo -e "a\nb\nc" > x ; ruby -pi -e '$_ = nil if $_ =~ /b/' x ; cat x

prints

a
c