使用sed查找字符串并替换该行,但忽略注释掉的行



我使用sed在300个不同配置的linux虚拟机上编辑我的/etc/samba/smb.conf文件。

我只想搜索未注释的"server string="行,并将整行替换为"server stringe=$VARIABLE SAMBA",它在读取我的服务器列表时从do while循环中获取VARIABLE。

所以尝试完成3件事1-找到"server string="并将该行替换为server string=$VARIABLE">

sed -i '/server string =/cserver string = '$VARIABLE' SAMBA' /etc/samba/smb.conf

上面的命令有效,但不幸的是,我的许多机器仍然有解释注释,其中还包括"server string=",我注意到未注释的"server strings="行并不总是在第1列中,而且在旧文件中经常有空格或选项卡,所以我不能只在它前面加^。

这是我在读取堆栈溢出的其他线程时想出的命令,并将替换行语法(\c(与忽略注释行语法(^#/!/(相结合,但这并不令人满意。我从另一个帖子中添加了"魔术替代"的\v,因为弄清楚到底需要逃脱什么让我难以捉摸。(我认为^和=需要逃脱(

sed -i -e '/^#/!s/vserver string =/cserver string = '$VARIABLE' SAMBA/g' /etc/samba/smb.conf

这句话现在似乎对我没有任何帮助。。。没有替换,没有变量替换。

如果我为"server string="grep,我会看到:(不,我不能手动更改所有308台机器(

# server string = is the equivalent of the NT Description field
server string = 145000web SAMBA ---- THIS LINE WAS NOT REPLACED ----

我对此束手无策。

-----------------------------

使用第一条评论提供的链接,我得到了这个:

sed '/^#/!s/test/TEST/g' file.txt - This command works as expected ignoring the commented out lines and replacing the text.

不幸的是,试图添加c来替换整行出错:

cTEST
# test
# test
cTEST
a cTEST to find cTEST

未注释的3行应该只显示TEST我试过在s/之后使用c\,这会导致所有替换都失败。

对于这样的文件:

# server string = is the equivalent of the NT Description field
server string = 145000web SAMBA1
#server string = is the equivalent of the NT Description field
server string = 999999web2 SAMBA2
#   server string = another comment
#          server string = more comments
server string = some value SAMBA3
server string = some value SAMBA4

和一个像这样的变量

echo $variable
111111www5

这将完成gnu-sed的工作,但没有保留空白:

sed 's/^[^#]*server string =.*/server string = '"$variable"' SAMBA/g' file
# server string = is the equivalent of the NT Description field
server string = 111111www5 SAMBA
#server string = is the equivalent of the NT Description field
server string = 111111www5 SAMBA
#   server string = another comment
#          server string = more comments
server string = 111111www5 SAMBA
server string = 111111www5 SAMBA

为了保留空白,你可以使用这样的东西:

sed -r 's/(^[^#]*)server string =.*/1server string = '"$variable"' SAMBA/g' file

甚至

sed -r 's/(^[^#]*server string =).*/1'"$variable"' SAMBA/g' file

附言:我故意启用了-i开关。当你对结果感到满意时,你可以添加它。

最新更新