[英]Grep perl regex works in terminal but not when executed from python
[英]Regex works in terminal but not in Perl script
這與這個問題有關
完成以反斜杠字符結尾的所有行的組合。 以下 Perl 命令在終端中有效,但在 Perl 腳本中無效:
perl -i -p -e 's/\\\n//' input_file
在 Perl 腳本中,我是這樣設置的,但它不起作用:
`perl -i -p -e 's/\\\n//' $input_file_path_variable`;
**更新了文件內容和使用的代碼
輸入文件內容如下:
foo bar \
bash \
baz
dude \
happy
所需 output 內容:
foo bar bash baz
dude happy
當前腳本:
#!/usr/bin/env perl
use Getopt::Long;
use FindBin;
use File::Path;
use File::Copy;
use DirHandle;
use FileHandle;
use File::Basename;
use Env;
use File::Slurp;
my $dummy_file = "/wdir/dummy.txt";
my $file_content = read_file($dummy_file);
print "$file_content\n";
print "==============================================\n"
my $ttest = $file_content =~ s/\\\n//;
print "$ttest\n";
當前 Output
foo bar \
bash \
baz
dude \
happy
==============================================
1
我想我意識到你的問題是什么。 您需要使您的替換匹配多次。
你正在使用這個單行:
perl -i -p -e 's/\\\n//' input_file
這將在逐行模式讀取的文件中每行替換一次反斜杠和換行符。 現在你正試圖在另一個程序中實現它,你正在將整個文件放入一個變量中,正如你對另一個答案的評論中提到的那樣:
我嘗試將整個文件讀入一個變量並應用您的解決方案,但對我不起作用:我的 $file_content = read_file($input_file_path_variable) 然后 $file_content =~ s/\\n//;
這只會更換一次。 文件中的第一個匹配項。 您需要添加修飾符/g
以使匹配盡可能多地成為全局匹配:
$file_content =~ s/\\\n//g;
我不確定你是如何使用你的代碼的,因為你沒有向我們展示。 這使得回答簡單的問題變得困難。 但如果我的假設是正確的,這將解決你的問題。
我認為自從最初提出問題以來,您至少更改了一次代碼/方法,但根據您當前的代碼,您的問題是這一行:
my $ttest = $file_content =~ s/\\\n//;
首先, s///
運算符在末尾需要一個g
以便它是全局搜索和替換,而不是在第一次替換后停止。
其次, $file_content =~ s/\\\n//
不返回最終字符串; 它就地修改字符串。 (因此它正在更改$file_content
。)在 Perl 的最新版本中,您可以在末尾添加一個r
修飾符以使其返回修改后的字符串。
所以這些中的任何一個都適合你:
my $ttest = ( $file_content =~ s/\\\n//gr );
要么:
( my $ttest = $file_content ) =~ s/\\\n//g;
生成您想要的 output 的完整腳本:
#!/usr/bin/env perl
use strict;
use warnings;
use File::Slurp;
my $file_content = read_file('/tmp/dummy.txt');
(my $ttest = $file_content) =~ s/\\\n//g;
print "$file_content\n";
print "==============================================\n";
print "$ttest\n";
在 Perl 你應該寫:
$input_file_variable =~ s/\\\n//;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.