编写Shell脚本:匹配模式后第3行末尾追加',somestring'
在匹配模式后第3行末尾追加字符串的Shell脚本方案
我来给你分享两个实用的方案,分别用sed和awk工具实现你的需求——在匹配到指定模式的行之后的第3行末尾追加,somestring。
使用sed实现
sed是处理文本流的经典工具,用它可以通过地址定位轻松完成这个操作。假设你要匹配的模式是somestuff anotherstuff, random,执行以下命令即可:
sed '/somestuff anotherstuff, random/{n;n;n;s/$/,somestring/}' your_file.txt
命令解释:
/somestuff anotherstuff, random/:定位到匹配目标模式的行{n;n;n}:连续执行三次n命令,读取并跳过接下来的3行,最终定位到匹配行后的第3行s/$/,somestring/:在当前定位到的行的末尾($表示行尾)替换成,somestring,实现追加效果
如果需要直接修改原文件(GNU sed环境),加上-i参数即可:
sed -i '/somestuff anotherstuff, random/{n;n;n;s/$/,somestring/}' your_file.txt
使用awk实现
awk更擅长处理结构化文本,我们可以通过跟踪行号来定位目标行:
awk '/somestuff anotherstuff, random/{target_line = NR + 3} NR == target_line {$0 = $0 ",somestring"} 1' your_file.txt
命令解释:
/somestuff anotherstuff, random/{target_line = NR + 3}:当匹配到目标模式时,记录目标行号为当前行号(NR)加3NR == target_line {$0 = $0 ",somestring"}:当遍历到目标行时,把行内容末尾拼接,somestring- 最后的
1:awk中1表示逻辑真,会触发默认的打印操作,确保所有行都被输出
如果需要修改原文件,可以用临时文件中转(避免直接写入导致的文件损坏):
awk '/somestuff anotherstuff, random/{target_line = NR + 3} NR == target_line {$0 = $0 ",somestring"} 1' your_file.txt > temp_file && mv temp_file your_file.txt
效果示例
假设你的原始文本是:
somestuff anotherstuff, random
line_1
line_2
line_3
line_4
执行命令后,文本会变成:
somestuff anotherstuff, random
line_1
line_2
line_3,somestring
line_4
内容的提问来源于stack exchange,提问作者Khalid
相关产品推荐
相关产品推荐

