简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM