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

With this simple snippet I am able to replace each occurence of dictionary key, with it's value, in a file. (Python)

Is there a similar way to go about in bash?

Exampple:

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

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


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

Wanted output (new content of file):"addMesh:"0x234544x0" addMesh="0x12353514x0"

:

for i in "${!dictionary[@]}"
do   
  echo "key  : $i"
  echo "value: ${dictionary[$i]}"
  echo
done
codeforester
  • 39,467
  • 16
  • 112
  • 140

2 Answers2

0

While there certainly are more sophisticated methods to do this, I find the following much easier to understand, and maybe it's just fast enough for your use case:

#!/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"

Assuming that the input file addMesh.txt contains

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

the resulting file will contain:

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

This method is not very fast, because it invokes sed multiple times. But it does not require sed to generate other sed scripts or anything like that. Therefore, it is closer to the original Python script. If you need better performance, refer to the answers in the linked question.

Andrey Tyukin
  • 43,673
  • 4
  • 57
  • 93
0

There is no perfect equivalent in Bash. You could do it in a roundabout way, given that dict is the associative array:

# 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
codeforester
  • 39,467
  • 16
  • 112
  • 140