这个awk命令做什么?

时间:2018-11-10 14:26:02

标签: awk

这个awk命令做什么?

awk 'NR > 1 {for(x=1;x<=NF;x++) if(x == 1 || (x >= 4 && x % 2 == 0)) 
printf "%s", $x (x == NF || x == (NF-1) ? "\n":"\t")}' depth.txt 
> depth_concoct.txt

我认为
NR > 1表示从第二行开始,
for(x=1;x<=NF;x++)表示每个字段,
if(x == 1 || (x >= 4 && x % 2 == 0))表示x等于1还是(我不了解此部分的代码,依此类推)
而且我知道awk的输入文件是depth.txt,而awk的输出将保存到depth_concoct.txt。 中间的代码是什么意思?

2 个答案:

答案 0 :(得分:1)

$ awk '
NR > 1 {                                     # starting from the second record
    for(x=1;x<=NF;x++)                       # iterate every field 
        if(x == 1 || (x >= 4 && x % 2 == 0)) # for 1st, 4th and every even-numbered field after 4th
            printf "%s",                     # print the field and after it 
                $x (x == NF || x == (NF-1) ? "\n":"\t")  # a tab or a newline if its the last field
}' depth.txt > depth_concoct.txt

(x == NF || x == (NF-1) ? "\n":"\t")被称为条件运算符,在这种情况下,它基本上是以下版本的简化版本:

if( x == NF || x == (NF-1) )  # if this is the last field to be printed
    printf "\n"               # finish the record with a newline
else                          # else
    printf "\t"`              # print a tab after the field

答案 1 :(得分:1)

您可以按如下所示重写它,应该很容易阅读。

$ awk `NR>1 {printf "%s", $1;  
             for(x=4;x<=NF;x+=2) printf "\t%s", $x;
             print ""}' inputfile > outputfile

代码的复杂性有时只是实现细节。

从第四位开始打印第一和第二个字段。

假设您的文件有8个字段,等效于

$ awk -v OFS='\t' 'NR>1{print $1,$4,$6,$8}' inputfile > outputfile
相关问题