sed命令注释掉文件中的文本

sed command to comment out text in file

我正在尝试用特定的词注释掉文件中的行。但是有多个行具有相似的词。

BBB-m      more info
BBB        more info
BBB-a      more info
BBB-w      more info

我想用 'BBB' 注释掉该行 这可能吗?谢谢!

sed -i -- 's/BBB/; BBB/g' $file

这应该可以解决问题:

sed -i 's/^[^#]*BBB$/#&/' file

& 字符匹配模式的整个部分,正如@Barmar 在评论中所说,BBB 末尾的 $ 过滤掉其他行。

您可以使用

awk ' == "BBB"{[=10=]="; "[=10=]}1' file > tmp && mv tmp file
sed 's/^BBB[[:space:]]/; &/' file > tmp && mv tmp file
sed -E 's/^BBB([[:space:]]|$)/; &/' file > tmp && mv tmp file

' == "BBB"{[=13=]="; "[=13=]}1' awk 命令表示如果第一个字段值等于 BBB,则在行首附加一个 ; 。否则,该行按原样输出。

's/^BBB[[:space:]]/; &/' sed 命令匹配以 BBB 和任何一个白色开头的行 space 然后替换为 ;, space 和匹配的文本。 -E POSIX ERE 变体 ^BBB([[:space:]]|$) 允许匹配 BBB 作为独立行。

参见 online demo:

#!/bin/bash
s='BBB-m      more info
BBB        more info
BBB-a      more info
BBB-w      more info'
awk ' == "BBB"{[=11=]="; "[=11=]}1' <<< "$s"
echo "---"
sed 's/^BBB[[:space:]]/; &/' <<< "$s"

两者都return

BBB-m      more info
; BBB        more info
BBB-a      more info
BBB-w      more info

使用sed

$ sed '/[[:punct:]]/!{s/BBB/; &/}' input_file
BBB-m      more info
; BBB        more info
BBB-a      more info
BBB-w      more info