Awk等效于perl

时间:2014-02-14 05:18:17

标签: perl awk gawk

我在命令行中了解perl,请帮帮我

在perl中等同于什么

awk '{for(i=1;i<=NF;i++)printf i < NF ? $i OFS : $i RS}' file

awk '!x[$0]++' file

awk 'FNR==NR{A[$0];next}($0 in A)' file1 file2

awk 'FNR==NR{A[$1]=$5 OFS $6;next}($1 in A){print $0,A[$1];delete A[$1]}' file1 file1

请有人帮助我......

1 个答案:

答案 0 :(得分:5)

尝试使用awk to perl翻译器。例如:

$ echo awk '!x[$0]++' file | a2p
#!/usr/bin/perl
eval 'exec /usr/bin/perl -S $0 ${1+"$@"}'
    if $running_under_some_shell;
            # this emulates #! processing on NIH machines.
            # (remove #! line above if indigestible)

eval '$'.$1.'$2;' while $ARGV[0] =~ /^([A-Za-z_0-9]+=)(.*)/ && shift;
            # process any FOO=bar switches

while (<>) {
    chomp;  # strip record separator
    print $_ if $awk;print $_ if !($X{$_}++ . $file);
}

您可以忽略开头的锅炉板,并在while循环中查看perl的肉。翻译很少是完美的(即使在这个简单的例子中,perl代码省略了换行符),但它通常提供了一个合理的近似值。

另一个例子(彼得在评论中遇到麻烦):

$ echo '{for(i=1;i<=NF;i++)printf( i < NF ? ( $i OFS ) : ($i RS))}'  | a2p
#!/usr/bin/perl
eval 'exec /usr/bin/perl -S $0 ${1+"$@"}'
    if $running_under_some_shell;
            # this emulates #! processing on NIH machines.
            # (remove #! line above if indigestible)

eval '$'.$1.'$2;' while $ARGV[0] =~ /^([A-Za-z_0-9]+=)(.*)/ && shift;
            # process any FOO=bar switches

$, = ' ';       # set output field separator

while (<>) {
    chomp;  # strip record separator
    @Fld = split(' ', $_, -1);
    for ($i = 1; $i <= ($#Fld+1); $i++) {
    printf (($i < ($#Fld+1) ? ($Fld[$i] . $,) : ($Fld[$i] . $/)));
    }
}