regex - sed - 注释与特定字符串匹配且尚未注释掉的行

我有以下测试文件

AAA
BBB
CCC

使用下面的 sed 我可以注释掉 BBB 行。

# sed -e '/BBB/s/^/#/g' -i file

如果该行的开头没有#,我只想注释掉它。

# sed -e '/^#/! /BBB/s/^/#/g' file

sed: -e expression #1, char 7: unknown command: `/'

有什么想法可以实现这一点吗?

最佳答案

假设您没有包含多个 # 的任何行,这将起作用:

sed -e '/BBB/ s/^#*/#/' -i file

注意:您不需要/g,因为您每行最多进行一次替换。

https://stackoverflow.com/questions/17998763/

相关文章:

linux - 如何使用调试版的 libc

linux - 在 Linux 中模拟/模拟 iOS

python - 在单行中打印不带括号的列表

python - 以 Unix 时间戳格式获取当前 GMT 时间的最简单方法是什么?

linux - ubuntu "No space left on device"但是有很多空间

python - 如何使用 Python 写入 Excel 电子表格?

python - 比较两个 DataFrame 并并排输出它们的差异

linux - 在 Linux 中注册文件扩展名/mime 类型

linux - 使用 Wget 发布请求?

python - Python中最有效的字符串连接方法是什么?