【问题标题】:Replace dictionary key in string with dictionary value用字典值替换字符串中的字典键
【发布时间】:2018-09-11 04:35:09
【问题描述】:
for key in dictionary:
    file = file.replace(str(key), dictionary[key])

通过这个简单的 sn-p,我可以在文件中用它的值替换字典键的每个出现。 (Python)

在 bash 中是否有类似的方法?

例子:

文件="addMesh:"0x234544" addMesh="0x12353514"

${!dictionary[i]}: 0x234544
${dictionary[i]}: 0x234544x0


${!dictionary[i]}: 0x12353514
${!dictionary[i]}: 0x12353514x0

想要的输出(文件的新内容):"addMesh:"0x234544x0" addMesh="0x12353514x0"

for i in "${!dictionary[@]}"
do   
  echo "key  : $i"
  echo "value: ${dictionary[$i]}"
  echo
done

【问题讨论】:

  • 你能提供更多关于键和值的信息吗?
  • @AndreyTyukin 已添加

标签: python bash


【解决方案1】:

虽然肯定有more sophisticated methods to do this,但我发现以下内容更容易理解,也许它对您的用例来说已经足够快了:

#!/bin/bash

# Create copy of source file: can be omitted
cat addMesh.txt > newAddMesh.txt

file_to_modify=newAddMesh.txt

# Declare the dictionary
declare -A dictionary
dictionary["0x234544"]=0x234544x0
dictionary["0x12353514"]=0x12353514x0

# use sed to perform all substitutions    
for i in "${!dictionary[@]}"
do   
  sed -i "s/$i/${dictionary[$i]}/g" "$file_to_modify"
done

# Display the result: can be omitted
echo "Content of $file_to_modify :"
cat "$file_to_modify"

假设输入文件addMesh.txt包含

"addMesh:"0x234544"
addMesh="0x12353514"

生成的文件将包含:

"addMesh:"0x234544x0"
addMesh="0x12353514x0"

这个方法不是很快,因为它会多次调用sed。但它不需要sed 来生成其他sed 脚本或类似的东西。因此,它更接近于原始 Python 脚本。如果您需要更好的性能,请参阅链接问题中的答案。

【讨论】:

    【解决方案2】:

    在 Bash 中没有完美的等价物。鉴于dict 是关联数组,您可以采用迂回的方式:

    # traverse the dictionary and build command file for sed
    for key in "${!dict[@]}"; do
      printf "s/%s/%s/g;\n" "$key" "${dict[$key]}"
    done > sed.commands
    
    # run sed
    sed -f sed.commands file > file.modified
    
    # clean up
    rm -f sed.commands
    

    【讨论】:

      猜你喜欢
      • 2022-01-15
      • 2017-07-15
      • 1970-01-01
      • 2020-08-04
      • 2017-08-24
      • 2021-01-02
      • 2020-09-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多