查找文本并将该行复制到文件中

时间:2013-01-25 20:37:39

标签: ruby

说我有这样的文本文件:

SELL USDCAD 0.99257 0.99653 0.39 -150.1 -8.57% -580.99 1 week ago  Copy 
SELL USDCAD 0.98986 0.99653 0.26 -177.2 -6.75% -457.25 1 week ago  Copy 
SELL USDCAD 0.98711 0.99653 0.17 -204.7 -5.10% -345.37 1 week ago  Copy 
BUY USDCAD 0.98613 0.98715 0.17 8.4 0.21% 14.47 1 week ago  Copy 

我正在寻找有一周前的#34;"这个字符串在里面。并将其转换为变量并写入另一个文本文件。

我该怎么做?

3 个答案:

答案 0 :(得分:2)

是否有任何理由你必须使用ruby,当命令行中的一行会做同样的事情?

grep '1 week ago' file.txt > newfile.txt

答案 1 :(得分:0)

你可以这样做:

str = <<EOT 
SELL USDCAD 0.99257 0.99653 0.39 -150.1 -8.57% -580.99 1 week ago  Copy 
SELL USDCAD 0.98986 0.99653 0.26 -177.2 -6.75% -457.25 1 week ago  Copy 
SELL USDCAD 0.98711 0.99653 0.17 -204.7 -5.10% -345.37 1 week ago  Copy 
BUY USDCAD 0.98613 0.98715 0.17 8.4 0.21% 14.47 1 week ago  Copy
EOT

content = str.lines.select { |l| l.include? '1 week ago' }.join("\n")
File.open('asdf.txt', 'w') { |file| file.write content }

答案 2 :(得分:0)

使用以下命令从命令行执行:

ruby -ne 'print if $_["1 week ago"]' < file_to_read > file_to_write