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

Sed 替换字符串并添加新行的Shell脚本,sed,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

我不熟悉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命令,但无法获得所需的输出。它不是跳过#行并附加它

sed -e "/abc.com/{h;s/^/##/P;x;G; /^#/!s/abc.com/xyz.com/;}" file1
有什么我遗漏的吗

请提供帮助,如有其他建议,我们将不胜感激

问候,,
桑托什这似乎是你想要的

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

这可能适合您(GNU-sed):


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

的第二行组成。您能更清楚地显示所需的输出吗?
*
是输入的一部分,还是所需输出的一部分?示例sed命令中没有任何内容在第一位工作时跳过带前导的
#
行。Etan-谢谢,这正是我无法隔离的内容。我已经相应地修改了输入和输出。现在我尝试了此命令,但它给了我错误sed:Function/^[^#].@abc.com/{h;s/^/#p;g;s/abc.com/xyz com/}无法解析。Hmm,在GNU sed为我工作。尝试在大括号前添加分号。谢谢Glenn。在添加了不区分大小写的sed后,它工作得非常好,我的意思是,就像如何用GNU sed替换搜索中的ABC.com XYZ.com一样,您将使用
s/../../../i
,否则您可能必须
s/[aA][bB][cC]\.com/XYZ.com/
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
    }
'
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
    }
'