【问题标题】:Shell script to replace string and add new line用于替换字符串并添加新行的 Shell 脚本
【发布时间】:2016-01-06 22:44:32
【问题描述】:

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

我有什么遗漏吗???

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

问候, 桑托什

【问题讨论】:

  • 你能更清楚地展示你想要的输出是什么吗? * 是输入的一部分还是所需输出的一部分?您的示例 sed 命令中的任何内容都不会跳过带有前导 # 的行以进行第一部分工作。
  • Etan - 谢谢,这正是我无法隔离的原因
  • 我现在已经相应地修改了输入输出

标签: sed


【解决方案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

【讨论】:

  • 我试过这个命令,但它给了我错误 sed: Function /^[^#].*@abc.com/ {h; s/^/##/; p; G; s/abc.com/xyz.com/} 无法解析。
  • 嗯,使用 GNU sed 为我工作。尝试在结束大括号前添加分号。
  • 谢谢格伦。添加分号后效果很好
  • sed 怎么做不区分大小写的,我的意思是如何在搜索中替换 ABC.com XYZ.com
  • 使用 GNU sed,你会使用s/.../.../i,否则你可能不得不使用s/[aA][bB][cC]\.com/xyx.com/
【解决方案2】:
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
    }
'

【讨论】:

    【解决方案3】:

    这可能对你有用(GNU sed):

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

    仅替换不以# 开头并包含abc.com 的行。替换的 RHS 包含以 ## 开头的原始行和字符串 abc.com 替换为 xyz.com 的第二行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-24
      • 1970-01-01
      • 2014-06-06
      • 2016-09-03
      相关资源
      最近更新 更多