【问题标题】:Inserting sequential numbers and line numbers for certain lines为某些行插入序号和行号
【发布时间】:2014-02-12 21:27:18
【问题描述】:

我正在尝试自动化以下过程:

  1. 在第 1 行 (0001) 插入一个数字
  2. 对于接下来的 25 行,插入连续的行号 (1-25) 和两个空格
  3. 在第 25 行之后,从第 1 行继续下一个序列号 (0002)
  4. 再次执行第 2 步
  5. 在此行号 25 之后,按顺序继续 (0003)
  6. 再次执行第 2 步

包含连续数字(0001、0002 等)的行将只包含数字,所以我假设需要添加回车。

是否也可以在编号行时在数字 1-9 之前包含一个空格,以便它们与 10-25 对齐?

比如……

0001
 1  This is text
 2  Some more text
 ↓
 9  Text here
10  Text here
 ↓
24  Additional text
25  And some more text
0002
 1  Text again
 2  More text
 ↓
 9  Text here
10  Text here
 ↓
24  Additional text
25  And some more text
0003

【问题讨论】:

    标签: regex bash awk terminal grep


    【解决方案1】:

    使用 awk

    awk 'FNR%25==1{printf "%04d\n",++i;s=1}{print s++,$0}' file
    

    【讨论】:

    • 第二个 print 也应该是 printf:awk 'FNR%25 == 1 {printf "%04d\n", ++i; s = 1}{printf "%2d %s\n", s++, $0}' 以便正确缩进 1-25 行号。
    【解决方案2】:

    有趣的问题,我得到了这一行,它提供了所需的格式化输出:

    awk '{s=(NR-1)%25}!s{printf "%04d\n", ++k}{printf "%2d %s\n",s+1,$0}' file
    

    【讨论】:

    • 完美运行。如何在行号 (1-25) 之后添加额外的空格?另外,关于了解更多关于awk 的任何建议?谢谢。
    • @jarhead "%2d %s\n" 你可以在%2d%s\n之间添加空格
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-22
    • 2019-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多