Ruby oneliner检查文件中是否存在多行

时间:2014-01-17 21:54:29

标签: ruby

我想要做的是创建一个Ruby oneliner来检查文件中是否存在多行。如果另外找到,则返回0返回码。

例如,如果我有一个名为/ tmp / foo的文件,其中包含以下内容。

one
two
three
four
five
six
seven

如果搜索字符串是'one \ ntwo \ nthree',那么它将返回0。 如果搜索字符串是'one \ two \ four',那么它将返回1.

我在网上发现了一堆例子如下,但主要是搜索/替换和搜索/打印。我不知道如何按摩它来做我想做的事。

ruby -i -e 'puts gets(nil).gsub(/${line}/,\"\")' ${file}
ruby -ne 'print -f ~/<regex>/' <file>

谢谢

2 个答案:

答案 0 :(得分:2)

这是一种方式。可能会更短:

ruby -e "exit(gets(nil) =~ %r{${line}} ? 0 : 1)" ${file}

示例电话:

ash@autumn ~ $ cat sample 
one
two
three
four
five
ash@autumn ~ $ ruby -e 'exit(gets(nil) =~ %r{one\ntwo\nthree} ? 0 : 1)' sample ; echo $?
0
ash@autumn ~ $ ruby -e 'exit(gets(nil) =~ %r{one\ntwo\nfour} ? 0 : 1)' sample ; echo $?
1

答案 1 :(得分:0)

File.read(filename).include?("one\ntwo\nthree") ? 0 : 1

doc = <<END
one
two
three
four
five
six
seven
END

filename = 'data'
File.write(filename, doc)

File.read(filename).include?("one\ntwo\nthree") ? 0 : 1 # => 0
File.read(filename).include?("one\ntwo\nfour")  ? 0 : 1 # => 1

从命令行:

ruby -e 'File.read("data").include?("one\ntwo\nthree") ? 0 : 1' # => 0