将数字添加到方括号之前每行的末尾

时间:2019-10-29 14:56:55

标签: linux string awk vim sed

需要在Linux中的主机文件的特定位置添加连续编号

awk '0==NR%2{$0} 1' FILE

正在尝试awk无法解决

[tab-edge]
101.55.12.199
[tab-edge]
101.55.12.193
[tab-edge]
101.55.12.194
[tab-edge]
101.55.12.192

预期结果

[tab-edge1]
101.55.12.199
[tab-edge2]
101.55.12.193
[tab-edge3]
101.55.12.194
[tab-edge4]
101.55.12.192

2 个答案:

答案 0 :(得分:2)

$ awk '{sub(/]/,(NR+1)/2"&")}1' file
[tab-edge1]
101.55.12.199
[tab-edge2]
101.55.12.193
[tab-edge3]
101.55.12.194
[tab-edge4]
101.55.12.192

答案 1 :(得分:0)

请您尝试以下。

awk '/\[tab/{sub(/\]$/,++count"&")} 1' Input_file

或者,如果每一行都从您要插入数字的[开始,而不是[tab,则尝试遵循。

awk '/^\[/{sub(/\]$/,++count"&")} 1'  Input_file


或者如果OP想要插入奇数行的计数,请尝试以下操作。

awk 'FNR%2!=0{sub(/\]$/,++count"&")} 1'  Input_file
相关问题