我有一个带有依赖项的文件。某些依赖项被注释 (#)。我想取消注释该行,如果它包含子字符串cassandra
.所以如果文件看起来像:
firstdependency>=2.0.7 # comment
otherdependency>=0.8.9 # another comment
#commenteddependency
#cassandra-driver>=2.1.4,!=3.6.0 # Apache-2.0
anotherdependency!=0.18.3,>=0.18.2
我想要一个只会将第四行更改为
cassandra-driver>=2.1.4,!=3.6.0 # Apache-2.0
所以它应该检查一行是否包含子字符串 cassandra
,如果是,检查该行的第一个字符是否等于 #
,如果是 - 删除该特定行的第一个字符 - 完成。我不知道该怎么做。帮助!
好吧,你知道从 sed
开始,那么这只是正确的替换命令的问题。
sed -e "s/^#(.*cassandra.*)$/1/"
查找遵循以下规则的行:
- 从
#
开始, - 在某处包含"Cassandra"(之前和之后都允许任意字符序列),
将行的所有其余部分(#
除外)存储在临时1
中(这就是(
... )
这样做),并被指示仅用后者替换这样的行。
如果需要,这可以进一步改进,例如在第二次出现#
后不查找"cassandra",但我认为您的示例中的结束行注释是由您添加的,不会有问题。
示例输出:
firstdependency>=2.0.7 # comment
otherdependency>=0.8.9 # another comment
#commenteddependency
cassandra-driver>=2.1.4,!=3.6.0 # Apache-2.0
anotherdependency!=0.18.3,>=0.18.2
简单与ed
,标准编辑器:
printf '%sn' 'g/^#.*cassandra/s/^#/' w | ed -s file >/dev/null
该命令g/^#.*cassandra/
标记以 #
开头并包含字符串的所有行cassandra
,s/^#/
删除这些标记行中的前导#
。
in awk.如果记录以#
开头并带有cassandra
,请在打印所有记录时删除前导#
:
$ awk '/^#/ && /cassandra/ { sub(/^#/,"") } 1' file
firstdependency>=2.0.7 # comment
otherdependency>=0.8.9 # another comment
#commenteddependency
cassandra-driver>=2.1.4,!=3.6.0 # Apache-2.0
anotherdependency!=0.18.3,>=0.18.2
您的脚本应仅包含以下行:
sed -e 's/#cassandra/cassandra/' your_file
正则表达式 s///用另一种模式替换一种模式,在本例中为 '#cassandra' 由 "cassandra" 替换。