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

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

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

问题

这是文件:

  1. -
  2. line1
  3. line2
  4. line3
  5. line4
  6. line5
  7. line6
  8. line7
  9. -
  10. line8
  11. line9
  12. line10
  13. line11
  14. line12
  15. line13
  16. line14
  17. -
  18. line15
  19. line16
  20. line17
  21. line18
  22. line19
  23. line20
  24. line21

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

  1. awk 'NR%6==1' file

它显示每6行的内容:

  1. -
  2. line6
  3. line11
  4. line16

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

  1. line6
  2. line12
  3. line18

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

英文:

This is the file:

  1. -
  2. line1
  3. line2
  4. line3
  5. line4
  6. line5
  7. line6
  8. line7
  9. -
  10. line8
  11. line9
  12. line10
  13. line11
  14. line12
  15. line13
  16. line14
  17. -
  18. line15
  19. line16
  20. line17
  21. line18
  22. line19
  23. line20
  24. line21

This is what I tried so far:

  1. awk 'NR%6==1' file

It shows every 6th line:

  1. -
  2. line6
  3. line11
  4. line16

But I expect this:

  1. line6
  2. line12
  3. 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,则打印当前行。

结果:

  1. 6
  2. 12
  3. 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 :

  1. line6
  2. line12
  3. line18

答案2

得分: 2

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

  1. $ awk -v n=6 '/^-/{c=0} c++ == n' file
  2. line6
  3. line13
  4. line20
  5. $ awk -v n=7 '/^-/{c=0} c++ == n' file
  6. line7
  7. line14
  8. line21
英文:

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

  1. $ awk -v n=6 '/^-/{c=0} c++ == n' file
  2. line6
  3. line13
  4. line20
  5. $ awk -v n=7 '/^-/{c=0} c++ == n' file
  6. line7
  7. line14
  8. line21

答案3

得分: 2

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

  1. 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:

  1. 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:

确定