【问题标题】:end of a file using awk in Unix在 Unix 中使用 awk 结束文件
【发布时间】:2013-03-31 10:40:27
【问题描述】:

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

【问题讨论】:

    标签: unix awk


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

    【讨论】:

    • +1 以获得良好的解决方案。对于 OP - 请注意 ENDFILE 仅在 GNU awk 的最新版本中可用,而不在任何其他 awk 中可用。如果您没有并且无法获得 gawk(尝试 - 这是非常值得的),您需要在 FNR==1 和 END 块中复制代码,或者构建一个数组以在 END 部分打印。跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-03
    相关资源
    最近更新 更多