【问题标题】:Replace key:value from one file in another file in shellscript?替换键:shell脚本中另一个文件中的一个文件的值?
【发布时间】:2014-01-28 20:31:27
【问题描述】:

我有一个包含键值条目的“数据库文件”,还有另一个文件,其中键出现在其他内容中。现在我想用我的键值文件的值替换那个关键字。示例:

有一个文件“keys.txt”和“关键字空间url”:

name1 https://maps.google.com
something http://www.domain.com/bla.php?value=500
blabla http://thisis.example.com/moooooar.asp

我有另一个文件“text.txt”,每行有一个或多个单词,如下所示:

notrelated somewhatrelated blabla
blabla unimportant
asdf asdf asdf name1 dadadada

因此我想要这样的东西:

notrelated somewhatrelated http://thisis.example.com/moooooar.asp
http://thisis.example.com/moooooar.asp unimportant
asdf asdf asdf https://maps.google.com dadadada

实际上,我的问题与https://stackoverflow.com/questions/5283653/ 非常相似,但由于我使用的是 URL(斜杠、冒号...),我猜那里提到的解决方案都没有解决?

【问题讨论】:

    标签: linux bash shell sed awk


    【解决方案1】:
    awk '
        NR==FNR {url[$1]=$2; next} 
        {for (i=1; i<=NF; i++) if ($i in url) $i=url[$i]; print}
    ' keys.txt text.txt 
    
    notrelated somewhatrelated http://thisis.example.com/moooooar.asp
    http://thisis.example.com/moooooar.asp unimportant
    asdf asdf asdf https://maps.google.com dadadada
    

    【讨论】:

    • 哇!太快!我无法与之竞争;)
    • 你能不能快点解释一下NR==FNR {url[$1]=$2; next}到底是做什么的,我听不懂。
    • 我知道! ;) - 它确保第一个命令块仅针对第一个文件 (keys.txt) 运行。 NR 是所有组合文件的输入记录计数器,FNR 是每个文件的输入记录计数器(每个文件重置)。只有在处理第一个文件时它们才会相等。
    【解决方案2】:

    好吧,这行得通(但如果你的键中有逗号,可能会中断):

    while read k v; do sed -e "s,$k,$v,g" -i text.txt; done < keys.txt
    

    【讨论】:

      猜你喜欢
      • 2016-04-14
      • 2019-03-06
      • 1970-01-01
      • 2018-03-29
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      • 2021-09-04
      相关资源
      最近更新 更多