【问题标题】:How to replace the links inside of a file by sed command如何通过 sed 命令替换文件内的链接
【发布时间】:2022-11-01 16:40:07
【问题描述】:

我有一个名为 1.txt 的文件,它包含以下 3 个 URL,每个 URL 都遵循一个 http 链接,我想使用 sed 命令更改它们。链接可以看作是一个没有空格的字符串。

  URL1: https://i.stack.imgur.com/Zw5ZK.png
  URL2: https://i.stack.imgur.com/cT8Pv.png
  URL3: https://i.stack.imgur.com/L3Syn.png

我的目的是使用类似下面的东西来替换命令行中的这 3 个链接,例如:

sed **** 1.txt https://abc/1.png https://abc/2.png https://abc/3.png

命令执行后,1.txt 的新内容为:

  URL1: https://abc/1.png
  URL2: https://abc/2.png
  URL3: https://abc/3.png

【问题讨论】:

    标签: linux sed


    【解决方案1】:

    像这样的东西?

    $ awk '{a=gensub(/URL([^:]+):/,"\1",1,$1);sub(/i.stack.imgur.com/.*/,"abc",$2);print $1,$2"/"a".png"}' 1.txt
    URL1: https://abc/1.png
    URL2: https://abc/2.png
    URL3: https://abc/3.png
    

    a=gensub(/URL([^:]+):/,"\1",1,$1) 捕获第一列中 URL 的数字部分。 sub(/i.stack.imgur.com/.*/,"abc",$2) 将第二列中的整个实际 url 替换为 https://abc

    print $1,$2"/"a".png" 使用新的编号 png 打印新行。

    【讨论】:

      【解决方案2】:

      使用sed

      $ sed -E 's~(URL([0-9]):[^:]*://).*~abc/.png~' input_file
      URL1: https://abc/1.png
      URL2: https://abc/2.png
      URL3: https://abc/3.png
      

      【讨论】:

        【解决方案3】:

        使用awk 更容易:

        awk 'BEGIN {FS=OFS="//"} {$2 = "abc/" ++n ".png"} 1' file
        
          URL1: https://abc/1.png
          URL2: https://abc/2.png
          URL3: https://abc/3.png
        

        使用sub 的替代awk 解决方案:

        awk '{sub(///.+/, "//abc/" ++n ".png")} 1' file
        
          URL1: https://abc/1.png
          URL2: https://abc/2.png
          URL3: https://abc/3.png
        

        【讨论】:

          【解决方案4】:

          这是一个简单的包装器,它将您的命令行参数更改为正确的sed 脚本。我们只是按行号索引。

          #!/bin/bash
          
          file=$1
          shift
          
          script=()  # empty array
          for ((i=1; i<=$#; i++)); do
              script+=(-e "${i}s|http.*|${!i}|")
          done
          sed "${script[@]}" "$file"
          

          【讨论】:

            猜你喜欢
            • 2017-08-23
            • 1970-01-01
            • 1970-01-01
            • 2013-09-25
            • 2021-12-14
            • 2020-09-22
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多