用字典值替换字符串中的字典键

时间:2018-04-01 22:20:45

标签: python bash

for key in dictionary:
    file = file.replace(str(key), dictionary[key])

通过这个简单的代码片段,我能够在文件中用它的值替换每个词典键的出现。 (Python)的

在bash中有类似的方法吗?

Exampple:

文件= "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

2 个答案:

答案 0 :(得分:0)

虽然肯定有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脚本。如果您需要更好的表现,请参阅链接问题中的答案。

答案 1 :(得分:0)

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