Perl 相当于 bash 命令



我不熟悉perl脚本,但我需要一个等效于以下bash行:

file1 包含一个包含多个单词的字符串,如下所示:

<Description>string string string</Description>

file2 包含第二列中有多个单词的字符串,如下所示:

Description         string string string
if [[ -e $file1 ]]; then
var1=cat $file1 | grep Description | sed 's/(.{13})//' | sed 's/.{14}$//'`
elif [[ -e $file2 ]]; then
var1=`cat $file2 | grep Description | cut -f2`
fi

我尝试过的代码:

if (-e file$1) {
$var1 .= perl -ne 'print if s/<Description.*>(.*?)</Description>/$1/g' file$1;
} else {
if (-e file$2){
$var1 .= perl -ne 'print if s/Description(.*?)/$1/g' file$2;
}
}

Perl 最初是作为胶水语言创建的。所以最简单的方法可能是像这样使用它:

my $var;
if (-e $file1) {
$var1 = `cat $file1 | grep Description | sed 's/(.{13})//' | sed 's/.{14}$//'`;
} elsif ( -e $file2 ) {
$var1 = `cat $file2 | grep Description | cut -f2`;
}

纯Perl中的东西需要打开文件并读取数据。

my $var;
if (-e $file1) {
open my $fh, '<', $file1 or die "Can't open '$file1': $!n";
while (<$fh>) {
if (/Description/) {
$var1 = $_;
$var1 =~ s/^.{13}//;
$var1 =~ s/.{14}^//;
}
}
} elsif ( -e $file2 ) {
open my $fh, '<', $file2 or die "Can't open '$file2': $!n";
while (<$fh>) {
if (/Description/) {
(undef, $var1) = split /s+/, $_, 2;
}
}
}

(我没有时间测试这些,所以可能会有小错别字。

最新更新