使用 awk 将计数器添加到字符串末尾的 header 行
Add Counter to header line at end of string using awk
我正在尝试将格式为### 的"page number" 添加到文件中每个header 行的末尾。 Header 行始终是相同的常量,但在整个文档中以随机间隔出现。我已经尝试使用 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
}
下面是需要完成的假设 input/output。
输入示例:
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
提前致谢!
使用 awk:
awk '/Header Line/ { [=10=] = [=10=] sprintf("\t%03d", ++n) } 1' filename
代码很简单:
/Header Line/ { # when a header line is found
[=11=] = [=11=] 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)
我正在尝试将格式为### 的"page number" 添加到文件中每个header 行的末尾。 Header 行始终是相同的常量,但在整个文档中以随机间隔出现。我已经尝试使用 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
}
下面是需要完成的假设 input/output。
输入示例:
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
提前致谢!
使用 awk:
awk '/Header Line/ { [=10=] = [=10=] sprintf("\t%03d", ++n) } 1' filename
代码很简单:
/Header Line/ { # when a header line is found
[=11=] = [=11=] 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)