Awk:使用行号和字数向后打印行

Awk:使用行号和字数向后打印行

使用 awk 命令,我要显示我创建的文件后面的第 3-5 行,并且在输出行之前显示行号(即第 3 行:)。我还要显示所有三行的总字数。下面提供了我的代码。我不断收到“%s”的错误消息,但不确定从这里该去哪里,有什么帮助吗?

BEGIN { print("<< Start of file >>"); }

NR>=3 && NR<=5 { for (i = NF; i >= 1; i--)

                printf "%d: %s ", $i;
                print ""
                wordCount += NF;


}



END { printf "<< End of file: wordCount = %d >>\n", wordCount }

这是输入文件:

Gimme presents I want more!
Gimme presents, I did my chores!
A bicycle, a tricycle, a motor vehicle!
I deserve it, you reverse it!
Gimme presents; more, more, more
Gimme presents I need more!

我得到的输出是:

(FILENAME=presents FNR=3) fatal: not enough arguments to satisfy format string
        `%d: %s '
             ^ ran out for this one

答案1

代码错误部分

关键问题是你有%d: %s格式,但只有一个参数$i可以匹配格式说明符,即$i匹配%d但不匹配%s

一旦你改变脚本如下:

#!/usr/bin/awk -f

BEGIN { print("<< Start of file >>"); }

NR>=3 && NR<=5 { 
    for (i = NF; i >= 1; i--)
        printf "%d: %s ", i,$i;
    print ""
    wordCount += NF;


}

END { printf "<< End of file: wordCount = %d >>\n", wordCount }

然后就没有错误了,并产生如下输出:

$ ./awk_script.awk input.txt
<< Start of file >>
7: vehicle! 6: motor 5: a 4: tricycle, 3: a 2: bicycle, 1: A 
6: it! 5: reverse 4: you 3: it, 2: deserve 1: I 
5: more 4: more, 3: more, 2: presents; 1: Gimme 
<< End of file: wordCount = 18 >>

修复代码以匹配所需的行为

然而,你的描述是:

我要显示我创建的文件后面的第 3-5 行,并且在输出行之前显示行号(即第 3 行:)

这意味着在使用 for 循环处理每个字段之前,您需要先输出行号:

#!/usr/bin/awk -f

BEGIN { print("<< Start of file >>"); }

NR>=3 && NR<=5 {
    printf "line %d:",NR; # display line number first
    for (i = NF; i >= 1; i--)
        printf " %s ", $i;
    print ""; 
    wordCount += NF;

}

END { printf "<< End of file: wordCount = %d >>\n", wordCount }

其工作原理如下:

$ ./awk_script.awk input.txt
<< Start of file >>
line 3: vehicle!  motor  a  tricycle,  a  bicycle,  A 
line 4: it!  reverse  you  it,  deserve  I 
line 5: more  more,  more,  presents;  Gimme 
<< End of file: wordCount = 18 >>

相关内容