尝试在shell命令下面运行perl脚本但是遇到错误,如何将这个shell命令转换为perl?
grep -i -e 'warn' test.txt | awk -F ':' '{print $2}' | grep -i '^[A-Z0-9]' | sort | uniq | sed 's/ *$//'
我已经尝试了第一部分的grep()函数,但是没有替代在perl中工作的awk命令。
答案 0 :(得分:2)
未测试:
#!/usr/bin/perl
use warnings;
use strict;
my %uniq;
open my $IN, '<', 'test.txt' or die $!;
while (my $line = <$IN>) {
next unless $line =~ /warn/i;
my $second_column = (split /:/, $line)[1];
if ($second_column =~ /^[0-9A-Z]/i) {
$second_column =~ s/ *$//;
$uniq{$second_column} = 1;
}
}
print "$_\n" for keys %uniq;
答案 1 :(得分:0)
展示如何将该shell命令的每个部分转换为perl:
use warnings;
use strict;
my %seen;
# grep -i -e 'warn' test.txt
local @ARGV = 'test.txt';
while (<>) {
next unless /warn/i;
# awk -F ':' '{print $2}'
chomp;
my $second_field = ( split /:/ )[1];
# grep -i '^[A-Z0-9]'
next unless $second_field =~ /^[A-Z0-9]/i;
# sed 's/ *$//'
$second_field =~ s/ +$//;
# uniq
$seen{$second_field}++;
}
# sort
print "$_\n" for sort keys %seen;
使用类似于shell的样式聚合成单个命令:
use List::MoreUtils qw(uniq);
local @ARGV = 'test.txt';
print "$_\n" for sort +uniq map {s/ +$//r} grep {/^[A-Z0-9]/i} map { chomp; ( split /:/ )[1] } grep {/warn/i} <>;