简体   繁体   English

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

[英]shell script to find and replace using sed command

I am new to shell scripting and have a request to modify multiple files. 我是Shell脚本的新手,并且有修改多个文件的请求。 I have the input as below 我有如下输入

#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

and need output like 需要像这样的输出

#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

I tried the below command to do this changes and it changes only abc to xyz and other are not getting changed 我尝试了以下命令进行此更改,并且它仅将abc更改为xyz,而其他未更改

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

Please help me to modify the script case-insentitive 请帮助我修改不区分大小写的脚本

You're asking how to do case insensitive matching and replacement. 您在问如何进行不区分大小写的匹配和替换。

There's no good and portable way of doing this with sed . sed做到这一点没有一种好的便携式方法。 You can instead use eg [Aa] to match either A or a : 您可以改用例如[Aa]来匹配Aa

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

You can rewrite this to a single substitution to save some bytes: 您可以将其重写为单个替换以节省一些字节:

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

However, if you're using GNU sed (and not eg OSX sed), then you can use the I flag to s : 但是,如果您使用的是GNU sed(而不是OSX sed),则可以将I标志用于s

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM