bash - 在文件中查找子字符串并注释该行并在注释行下方插入新行
问题描述
我正在尝试--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 脚本!
解决方案
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
推荐阅读
- python - 将 numpy 矩阵转换为单列 pandas
- python - 更改在 Python 3 中打开 stdin/stdout 的方式
- java - 未提交的消息不再被消费
- firebase - 如何在 Firestore 事务中实现 getOrCreate?
- python - 如何从 openpyxl 中的列对象中提取单元格值?
- r - 如何订购 R H2O 中因子的水平
- vba - 在 VBA 中比较两个字典之间的数据
- reactjs - 遇到 API 调用的 React 错误
- oracle - Oracle Apex 动态标题取决于 sql
- gitlab - 如何在 gitlab-ci.yml 中指定我的本地 .bat 文件(在 Gitlab 服务器上运行)?