0

我在使用 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
4

1 回答 1

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每个文件的结尾和结尾,否则您将获得所有文件的运行总数。

于 2013-03-31T13:46:02.710 回答