Perl替代在Ruby%x{}中使用的未被请求时插入垃圾

Perl替代在Ruby%x{}中使用的未被请求时插入垃圾,ruby,perl,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") 我的目标是去除每一行的所有

所以我经营的是一家班轮公司:

 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>

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

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

无法重现您的问题。我得到了“811233”(带换行符)。看起来你的一个反斜杠不在那里。例如
[^d\n]
而不是你写的。它在这里工作得很好。@texasbruce只是好奇:为什么?@sidyll Windows无法区分竖条是否是管道,即使它们被引用了。使用新的编辑:天哪,这是一个非常奇怪的计算。。。为什么不一直使用perl呢?不能重现您的问题。我得到了“811233”(带换行符)。看起来你的一个反斜杠不在那里。例如
[^d\n]
而不是你写的。它在这里工作得很好。@texasbruce只是好奇:为什么?@sidyll Windows无法区分竖条是否是管道,即使它们被引用了。使用新的编辑:天哪,这是一个非常奇怪的计算。。。为什么不一直使用perl呢?
%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}