首页 > 解决方案 > 在文件中查找子字符串并注释该行并在注释行下方插入新行

问题描述

我正在尝试--port 1234在文件中查找子字符串,如果该行未注释,则注释掉该行#并在其下方插入一个新行,定义为this is the new path: /new/path/to/file. 如果包含的行--port 1234已被注释,则什么也不做。如果--port 1234在文件中找不到子字符串,则echo "not found"

样本输入:

somecode somecode
somecode somecode --port 1234 somecode somecode somecode
somecode somecode

样本输出:

somecode somecode
#somecode somecode --port 1234 somecode somecode somecode
This is the new path: /new/path/to/file
somecode somecode

这是我到目前为止所拥有的:

sed -E '/--port 1234/!b;/^[^#]/!b;

到目前为止,我只知道如果该行已被注释,或者如果一行不包含--port 1234. 非常新的 bash 脚本!

标签: bashunixawksedgrep

解决方案


awk更适合这份工作。

示例文件:

cat file

foo bar
#somecode somecode --port 1234 somecode somecode somecode
somecode somecode
somecode somecode --port 1234 somecode somecode somecode
somecode somecode

用作gnu awk

awk -i inplace '/--port 1234 / && !/^#/ {
   print "#" $0 ORS "This is the new path: /new/path/to/file"
   next
} 1' file

foo bar
#somecode somecode --port 1234 somecode somecode somecode
somecode somecode
#somecode somecode --port 1234 somecode somecode somecode
This is the new path: /new/path/to/file
somecode somecode

推荐阅读