【问题标题】:Add Counter to header line at end of string using awk使用 awk 将计数器添加到字符串末尾的标题行
【发布时间】:2015-03-25 04:11:57
【问题描述】:

我正在尝试将### 格式的“页码”添加到文件中每个标题行的末尾。标题行始终是相同的常数,但在整个文档中以随机间隔出现。我曾尝试使用 SED 和 AWK,但我愿意接受所有建议。我尝试了为我的问题量身定制的以下 sudo 代码

counter=0
max = find number of Header Line string
while reading 
       for (i =0; i< Pagemax;i++)
{
replace string Header Line with page counter
counter+1
}

以下是需要完成的假设输入/输出。

输入示例:

Header Line     
Dolphin
Whale
Fish
Header Line     
Bird
Header Line     
Bus
Skate Board
Bike

期望的输出:

Header Line     001
Dolphin
Whale
Fish
Header Line     002
Bird
Header Line     003
Bus
Skate Board
Bike

提前致谢!

【问题讨论】:

    标签: bash shell awk sed


    【解决方案1】:

    使用 awk:

    awk '/Header Line/ { $0 = $0 sprintf("\t%03d", ++n) } 1' filename
    

    代码很简单:

    /Header Line/ {                   # when a header line is found
      $0 = $0 sprintf("\t%03d", ++n)  # increase the counter n and append a tab
                                      # followed by it (formatted appropriately)
                                      # to the line
    }
    1                                 # then print (non-header lines will be
                                      # printed unchanged)
    

    【讨论】:

    • 使用print $0, sprintf(...); next 使用OFS 可能会更好,但我不知道OP到底想要什么。
    • 我想我更喜欢$0 = $0 OFS sprintf("%03d", ++n),但我同意如果脚本变得更复杂,这可能是一个改进。
    • FWIW 我会使用 $0 = sprintf("%s%s%03d", $0, OFS, ++n) 而不是 sprintf 加上一个连接,但 nbd...
    猜你喜欢
    • 2021-01-04
    • 1970-01-01
    • 2012-08-03
    • 1970-01-01
    • 1970-01-01
    • 2013-02-02
    • 1970-01-01
    • 1970-01-01
    • 2014-03-06
    相关资源
    最近更新 更多