Search code examples
rubyinplace-editing

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


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?


Solution

  • 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