简体   繁体   English

如何使用Ruby的命令行就地编辑模式从文本文件中删除行

[英]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的长期用户,在perl中,您可以像这样轻松地从文本文件中删除行:

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,该脚本也进行就地编辑,所以我这样写:

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 . 如果它不起作用,则说明问题在some-condition To demonstrate, 展示,

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

prints 版画

a
c

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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