Bash 使用awk将计数器添加到字符串末尾的标题行
我正试图在文件的每一行标题末尾添加一个格式为####的“页码”。标题行始终保持不变,但在整个文档中以随机间隔出现。我曾尝试使用SED和AWK来实现这一点,但我愿意接受所有建议。我尝试了以下针对我的问题定制的sudo代码Bash 使用awk将计数器添加到字符串末尾的标题行,bash,shell,awk,sed,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=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 001
Dolphin
Whale
Fish
Header Line 002
Bird
Header Line 003
Bus
Skate Board
Bike
提前谢谢 使用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(…);下一步
使用OFS
但我不知道OP到底想要什么。我想我更喜欢$0=$0 OFS sprintf(“%03d”,++n)
,但我同意如果脚本变得更复杂,这可能是一种改进。FWIW我会使用$0=sprintf(“%s%s%03d”,$0,OFS,++n)
,而不是sprintf加上一个连接,但是nbd。。。
/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)