[英]shell command to perl script with awk, grep
嘗試在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命令。
未經測試:
#!/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;
顯示一個人如何可能將該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} <>;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.