在Unix中使用awk的文件结尾

时间:2013-03-31 10:40:27

标签: unix 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) //this is supposed to show when the file is over but it's not working
{           //I also tried if (FNR == 1) - which means new file
 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 个答案:

答案 0 :(得分:1)

这就是你需要的:

length($0) >= 10 {                             
    print "The number of line is:",FNR 
    print "The content of the line is:",substr($0,11)
    count++                                              
}
ENDFILE {                        
    print "This was the analysis of the file:",FILENAME
    print "The number of lines with characters >= 10 are:",count
    count = 0
}

将其另存为script.awk,然后像awk -f script.awk file1 file2 file3一样运行。

注意:

  • 对于行长度,要求the number of lines that has the length at least 10应为>=10

  • except the fist 10 characters表示您希望从{11}开始substr($0,11)

  • 条件length($0) >= 10应该在块之外完成。

  • 您需要使用特殊的ENDFILE块在每个文件的末尾打印分析。

  • 您需要重置count和每个文件的结尾,否则您将获得所有文件的总计。