【问题标题】:Find - replace - Update string using shell script查找 - 替换 - 使用 shell 脚本更新字符串
【发布时间】:2014-06-06 13:18:09
【问题描述】:

我有一个文件,其中包含类似的行

https://abcdefgh.com/123/pqrst/456/xyz.html

所以我想在该文件中搜索这一行并将结尾部分,即xyz.html 替换为mno.html

将mno.html 作为 shell 脚本的输入。

怎么做?

【问题讨论】:

    标签: shell unix replace awk grep


    【解决方案1】:
    $ awk 'BEGIN{FS=OFS="/"} index($0,"https://abcdefgh.com/123/pqrst/456/xyz.html"){$NF="mno.html"} 1' file
    https://abcdefgh.com/123/pqrst/456/mno.html
    

    或者如果两个值都已经存储在 shell 变量中:

    $ old="https://abcdefgh.com/123/pqrst/456/xyz.html"
    $ new="mno.html"
    $ awk -v old="$old" -v new="$new" 'BEGIN{FS=OFS="/"} index($0,old){$NF=new} 1' file
    https://abcdefgh.com/123/pqrst/456/mno.html
    

    【讨论】:

      【解决方案2】:

      你可以用这个sed,

      sed '/https:\/\/abcdefgh.com\/123\/pqrst\/456\/xyz.html/s#\(.*\/\)\(.*\)#\1mno.html#g' yourfile
      

      【讨论】:

      • 您应该转义.com 和.html 中的.。还值得告诉 OP,他们需要转义所有其他可能出现在文件名中的 RE 元字符等(例如 *)。
      【解决方案3】:

      如果该行与示例完全相同,则使用awk,我的意思是它之前或之后没有其他字符

      awk '{print gensub(/^(https:\/\/abcdefgh.com\/123\/pqrst\/456\/)xyz.html$/,"\\1mno.html","g")}' input.txt
      

      否则:

      awk '{print gensub(/(https:\/\/abcdefgh.com\/123\/pqrst\/456\/)xyz.html/,"\\1mno.html","g")}' input.txt
      

      【讨论】:

      • 您应该提到这是特定于 GNU awk 的。您应该转义 .com 和 .html 中的 .。还值得告诉 OP,他们需要转义所有其他可能出现在文件名中的 RE 元字符等(例如 *)。不过,老实说,如果我要使用 RE 替换方法,我只会使用 sed,并且不必转义一堆字符。
      猜你喜欢
      • 1970-01-01
      • 2012-11-02
      • 2016-09-03
      • 2014-11-24
      • 2015-05-05
      • 1970-01-01
      • 2014-02-17
      • 1970-01-01
      • 2016-03-18
      相关资源
      最近更新 更多