[英]How to pass a replacing regex with a backreference as a command line argument to a Perl script
[英]Perl regex script and command line different
所以我試圖從日志行中刪除嵌入\\ n而不從命令行中刪除每個日志行的\\ n。 我試過這些,他們都改變了所有\\ n到〜。
cat test1.txt | perl -n -e 's{\n(?!2013)}{~}mg;print' > test1a.fix
perl -n -e 's{\n(?!2013)}{~}mg;print' test1.txt > test1b.fix
所有人都忽略了背后的負面看法
test1.txt包含
2013-03-01 12:23:59,1
line2
line3
2013-03-01 12:23:59,4
包含test1a.fix和test1b.fix
2013-03-01 12:23:59,1~line2~ line3~2013-03-01 12:23:59,4
但我使用這個腳本想出了正則表達式。
#!/usr/bin/perl
use warnings;
use strict;
sub test {
my ($str, $expect) = @_;
my $mod = $str;
$mod =~ s{\n(?!2013)}{~}mg;
print "Expecting '$expect' got '$mod' - ";
print $mod eq $expect ? "passed\n" : "failed\n";
}
test("2013-03-01 12:23:59,line1
line2
line3
2013-03-01 12:23:59,line4", "2013-03-01 12:23:59,line1~line2~ line3
2013-03-01 12:23:59,line4");
它會產生符合我想要的以下輸出。
sfager@linux-sz05:~/logs> ./regex_test.pl
Expecting '2013-03-01 12:23:59,line1~line2~ line3
2013-03-01 12:23:59,line4' got '2013-03-01 12:23:59,line1~line2~ line3
2013-03-01 12:23:59,line4' - passed
sfager001@linux-sz05:~/logs>
誰能解釋為什么這些工作方式不同以及如何在命令行上完成?
perl -n
處理一行文件。 當它讀取一行時,換行符位於字符串的末尾,而不是您的正則表達式所期望的開頭。 您應該使用^
來匹配行的開頭而不是\\n
。
在函數版本中,您將立即處理整個多行字符串。 在這種情況下,換行符位於字符串的中間,並且它們與正則表達式匹配。
您的命令行程序一次只能看到一個“輸入記錄”(也就是行)。 通過重寫輸入記錄分隔符變量$ /,我能夠讓你的例子工作。
perl -n -e '$/=undef; s{\n(?!2013)}{~}mg;print' test1.txt > test1c.fix
這將重新定義每個“行”作為整個輸入,實際上使其更像腳本。
cat test1c.fix
2013-03-01 12:23:59,1~line2~ line3
2013-03-01 12:23:59,4~
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.