Shell脚本替换字符串并添加新行

时间:2016-01-05 19:14:00

标签: sed

我是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

我尝试了下面的sed命令,但无法获得所需的输出。它不会跳过#line并附加它。

sed -e "/abc.com/{h;s/^/##/P;x;G; /^#/!s/abc.com/xyz.com/;}" file1

有什么我想念的吗?

请帮助,任何其他建议也将不胜感激。

此致 桑托什

3 个答案:

答案 0 :(得分:1)

这似乎是你想要的

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

等效的awk:

awk '/^[^#].*abc.com/ {print "##" $0; sub(/abc.com/, "xyz.com")};1'

小心翼翼地,应该转义点:abc\.com

答案 1 :(得分:0)

这可能适合你(GNU sed):

sed 's/^\([^#].*\)abc\.com/##&\n\1xyz.com/' file

仅替换不以#开头且包含abc.com的行。替换的RHS由##前面的原始行和abc.com替换字符串xyz.com的第二行组成。

答案 2 :(得分:0)

sed '
    /^#/n; 
    /.*abc.com/{
        h;  # hold this line to HOLD SPACE
        s/abc.com/xyz.com/;  # modify
        x;  # exchange PATTERN with HOLD
        s/^/##/;  
        G;  # get
    }
'