使用awk将字符串添加到字符串末尾的标题行

时间:2015-03-24 20:02:57

标签: bash shell awk sed

我正在尝试将格式为###的“页码”添加到我文件中每个标题行的末尾。标题行始终是相同的常量,但在整个文档中以随机间隔出现。我尝试使用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

提前致谢!

1 个答案:

答案 0 :(得分:2)

使用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)