Perl替换在Ruby%x {}中没有被问到的时候插入垃圾

时间:2012-10-25 20:34:02

标签: ruby perl

所以我正在运行这个班轮:

 perl -i -pe 's|[^\d\n]||g' country-ids.txt

替换文本中的文本,如下所示:

# encoding: utf-8
files_to_change = ["db_owners.txt", "db_vessels.txt"]
files_to_change.each do |file|
    text = File.read(file)
,"1")
,"1")
,"2")
,"2")
,"3")

我的目标是去除所有非数字字符的每一行,同时将线条保持在原始位置。

而不是我想要的结果,我得到了这个:

d
dd
d
d
<blank space>

不确定发生了什么。我保留新行的原因是因为我最后一次运行它而没有“查找”字符类中的换行符我得到的只是一个非常非常长的数字行。

我使用%x {command}在.rb脚本中运行它,如果这有任何区别的话。

编辑:

这是整个脚本。仍然遇到同样的问题。不知道为什么。

%x{cut -f 2 -d/ script-substitute-countries-with-id.rb > countries2.txt}
%x{cut -f 2 db_vessels.txt > countries.txt}
%x{cut -f 3 -d/ script-substitute-countries-with-id.rb > country-ids.txt}
%x{perl -i -pe 's:[^\d]::g' country-ids.txt}
%x{join countries2.txt country-ids.txt > countries2.txt.tmp}
%x{mv countries2.txt.tmp countries2.txt}
%x{cat countries.txt countries2.txt > countries.txt}
%x{uniq countries.txt > countries.txt.tmp}
%x{mv countries.txt.tmp countries.txt}

1 个答案:

答案 0 :(得分:5)

Ruby的%x{}运算符应用双引号语义,这意味着反斜杠是特殊的。将perl代码更改为:'s|[^\\d\\n]||g'(每个地方使用2个反斜杠1),它应该可以正常工作。