如何分组并显示每组的第n行。

huangapple go评论43阅读模式
英文:

How to group lines and show every nth line of that group

问题

这是文件:

-
line1
line2
line3
line4
line5
line6
line7
-
line8
line9
line10
line11
line12
line13
line14
-
line15
line16
line17
line18
line19
line20
line21

这是我到目前为止尝试的:

awk 'NR%6==1' file

它显示每6行的内容:

-
line6
line11
line16

但我期望的是这样的结果:

line6
line12
line18

文件的行被每7行的连字符 "-" 分组,就像示例一样。

英文:

This is the file:

-
line1
line2
line3
line4
line5
line6
line7
-
line8
line9
line10
line11
line12
line13
line14
-
line15
line16
line17
line18
line19
line20
line21

This is what I tried so far:

awk 'NR%6==1' file

It shows every 6th line:

-
line6
line11
line16

But I expect this:

line6
line12
line18

The file lines are grouped by - each 7th line as the example.

答案1

得分: 2

`awk '/^-/{group++;next}' - 当一行以“-”开头时,增加组计数器并跳到下一行。

group && ((NR-group)%6==0){print} - 如果我们处于一个组中(即group不为0),并且当前行号减去组号模6等于0,则打印当前行。

结果:

第6行
第12行
第18行
英文:

you can solve it like this :

awk '/^-/{group++;next} group && ((NR-group)%6==0){print}' file

  • '/^-/{group++;next}' - When a line starts with "-", increment the group counter and skip to the next line.
  • 'group && ((NR-group)%6==0){print}' - If we are in a group (i.e., group is not 0) and the current line number minus the group number modulo 6 is 0, print the current line

Result :

line6
line12
line18

答案2

得分: 2

如果您真的想打印每个组的第n行,那么可以使用以下命令:

$ awk -v n=6 '/^-/{c=0} c++ == n' file
line6
line13
line20

$ awk -v n=7 '/^-/{c=0} c++ == n' file
line7
line14
line21
英文:

If you really wanted to print the nth line of every group then it'd be:

$ awk -v n=6 '/^-/{c=0} c++ == n' file
line6
line13
line20

$ awk -v n=7 '/^-/{c=0} c++ == n' file
line7
line14
line21

答案3

得分: 2

对于每一行不是分隔符的行,递增一个计数器。如果递增后的计数器可以被6整除,就打印该行:

awk '$0 != "-" && ++c % 6 == 0'
英文:

For every line which is not the separator, increment a counter. If the incremented counter is divisible by 6, print the line:

awk '$0 != "-" && ++c % 6 == 0'

huangapple
  • 本文由 发表于 2023年6月18日 19:49:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76500393.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定