计算文件每个块的非空行数,其中多个块由空行分隔
我想计算一个文件中的行数,该文件由多个块(例如 3 个)组成,每个块都有不同的行数。每个块由空行分隔。有单行解决方案吗? 到目前为止,这是我所拥有的:
awk '(NR>4) && NF!=0 {++count} END {打印计数}' 文件名 > outfile
这显然会计算所有非空白行(并消除 4 行标题)。我现在必须包含一个 for 循环,每次运行后它应该打印行数。
因此,如果我有 100 个非空行,并且第一个块包含 20 行,第二个 50 行和第三个 30 行,则理想的输出将是 20 50 30
到目前为止我的所有努力都存在语法错误。
感谢您的帮助 汤姆
I'd like to count lines in a file that consists of several blocks, say 3, each with a different number of lines. Each block is separated by a blank line. Is there a one line solution?
So far here is what I have:
awk '(NR>4) && NF!=0 {++count} END {print count}' filename > outfile
This obviously counts all non-blank lines (and gets rid of a 4-line header). I now have to include a for loop and after each run it should print the number of lines.
So if I have 100 non-blank lines, and the first block contains 20 lines, the second 50 and the third 30 lines, the ideal output would be 20 50 30
All my effort so far had syntax errors.
Thanks for your help
Tom
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
会做的。
注意:我使用
printf
因为您已将输出指定为“20 50 30”,它位于一行。编辑:刚刚识别,我们必须跳过前4行。
would do it.
Note: I'm using
printf
because you had specified the output as "20 50 30" which is on one line.Edit: just recognized, we must skip the first 4 lines.
如果我理解正确的话(下次显示示例)
所以基本上,在到达记录 4 之前的记录 3 处,将记录分隔符设置为空白,将字段分隔符设置为换行符。这是因为我们不想触及标题行的 RS 和 FS 变量。在第 3 行之后,我们需要更改 RS 和 FS,以便获得所需的结果。即,一条记录以空行结尾,所有字段均以换行符“\n”分隔,本质上,计算 NF 将得到一条记录中的总行数。
if i get you correctly (next time show examples)
So basically, at record 3 just before reaching record 4, set the record separator to blank and field separator to newlines. This is because we don't want to touch the RS and FS variables for the header lines. AFter the 3rd line, we need to change the RS and FS so that we get desired result. ie, a record ends with a blank line and all fields are separated by newlines "\n", essentially, counting NF will get us the total number of lines in one record.
这是我的文件的一个版本:
它以空行开头:
是的,末尾有一个空行
THX
Here is a version of my file:
It starts with a blank line:
Yes there is a blank line at the end
THX