使用awk时出现问题

使用awk时出现问题

我在使用 awk 时遇到问题。从作为参数给出的每个文件中打印长度至少为 10 的行数。此外,打印该行的内容(前 10 个字符除外)。在文件分析结束时,打印文件名和打印的行数。

这是我到目前为止所做的:

{
if(length($0)>10)
{
 print "The number of line is:" FNR
 print "The content of the line is:" substr($0,10)
 s=s+1
}
x= wc -l //number of lines of file
if(FNR > x) 
{
 print "This was the analysis of the file:" FILENAME
 print "The number of lines with characters >10 are:" s
}
}

这会打印文件名以及每行后至少有 10 个字符的行数,但我想要这样的内容:

print "The number of line is:" 1
print "The content of the line is:" dkhflaksfdas
print "The number of line is:" 3
print "The content of the line is:" asdfdassaf
print "This was the analysis of the file:" awk.txt
print "The number of lines with characters >10 are:" 2

答案1

尝试这样的事情:

#!/usr/bin/gawk -f
{
    ## Every time we change file, print the data for
    ## the last file read (ARGV[ARGIND-1])
    if(FNR==1 && ARGIND>1){
        print "This was the analysis of file:" ARGV[ARGIND-1]
        print "The number of lines with >10 characters is:" s,"\n"
        s=0;
    } 
    if(length($0)>10){
        print "The line number is:" FNR
        print "The content of the line is:" substr($0,10)
        s=s+1   
    }
}
## print the data collected on the last file in the list
END{
    print "This was the analysis of file:" ARGV[ARGIND]
    print "The number of lines with >10 characters is:" s,"\n"
}

如果您对文件运行此命令ab并且c

$ ./foo.awk a b c
The line number is:2
The content of the line is:kldjahlskdjbasd
This was the analysis of the file:a
The number of lines with characters >10 is:1 

The line number is:2
The content of the line is:ldjbfskldfbskldjfbsdf
The line number is:3
The content of the line is:kfjbskldjfbskldjfbsdf
The line number is:4
The content of the line is:ldfbskldfbskldfbskldbfs
The line number is:5
The content of the line is:lsjdbfklsdjbfklsjdbfskljdbf
This was the analysis of the file:b
The number of lines with characters >10 is:4 

The line number is:1
The content of the line is: asdklfhakldhflaksdhfa
This was the analysis of the file:c
The number of lines with characters >10 is:1 

答案2

您可以将文件结束摘要放在一个END {...}块中 - 它将在脚本退出时执行。

即摆脱假的x=wc -l并将其更改if (FNR > x) { ... }为只是END { ... }

相关内容