我们有以下文件
more /tmp/file
number_of_cars_are=$number_of_cars_are
LOG "number_of_cars_are=$number_of_cars_are"
echo "number_of_cars_are are $number_of_cars_are"
grep number_of_cars_are /tmp/test
我们只想注释以number_of_cars_are=
& 开头的行,如果该行已经是注释,那么 sed 应该忽略
所以我们做了以下事情
sed '/^[^#].*^[[:space:]]*number_of_cars_are=/ s/^/#/' /tmp/file
但行 - number_of_cars_are=$number_of_cars_are 保持不变
预期成绩
more /tmp/file
# number_of_cars_are=$number_of_cars_are
LOG "number_of_cars_are=$number_of_cars_are"
echo "number_of_cars_are are $number_of_cars_are"
grep number_of_cars_are /tmp/test
答案1
您用来匹配行的正则表达式有两个行首锚点 ( ^
),因此第二个锚点仅匹配实际^
符号。如果删除^
before [[:space:]]
,表达式将匹配,但匹配太多:
# number_of_cars_are=$number_of_cars_are
# LOG "number_of_cars_are=$number_of_cars_are"
LOG "
匹配.*
,因此被接受。我会删除表达式的开头:
sed '/^[[:space:]]*number_of_cars_are=/ s/^/#/'
这匹配以任意数量的空白字符(包括无)开头,后跟 的任何行number_of_cars_are=
。注释行不会与此匹配,因此不会再次处理它们,并且直接以 开头的行将number
匹配。