用于使用sed命令查找和替换的shell脚本

时间:2016-01-21 20:17:23

标签: shell

我是shell脚本的新手,并且有一个修改多个文件的请求。我有 输入如下

#this is line1 for file1@abc.com     
test line 2  
test line 3  
this is line4 for file1@ABC.com  
test line 5  
this is line6 for file1@Abc.COM

需要输出

#this is line1 for file1@abc.com   
test line 2  
test line 3   
##this is line4 for file1@ABC.com  
this is line4 for file1@XYZ.com  
test line 5   
##this is line6 for file1@Abc.COM  
this is line6 for file1@Xyz.COM

我尝试了以下命令来执行此更改,它只将abc更改为xyz而其他命令没有更改

sed '/^[^#].*@abc.com/ {h; s/^/##/; p; g; s/abc.com/xyz.com/;}'

请帮我修改脚本案例 - 代理

1 个答案:

答案 0 :(得分:1)

您正在询问如何进行不区分大小写的匹配和替换。

使用sed执行此操作没有好的便携方法。你可以改用例如[Aa]匹配Aa

sed '/^[^#].*@[Aa][Bb][Cc]\.[Cc][Oo][Mm]/ {
        h; s/^/##/; p; g; s/[Aa][Bb][Cc]\.[Cc][Oo][Mm]/xyz.com/;
     }'

您可以将其重写为单个替换以节省一些字节:

sed 's/^\([^#].*\)[Aa][Bb][Cc]\.[Cc][Oo][Mm]\(.*\)/##&\
\1xyz.com\2/'

但是,如果您使用的是GNU sed(而不是OSX sed),那么您可以使用I标记s

sed 's/^\([^#].*\)abc\.com\(.*\)/##&\n\1xyz.com\2/I'  # GNU only
相关问题