3

I'm having a custom xml and im trying to replace a multiple occurring string (say "uuidVariable") with a unique UUID each in Bash.

<dict>
    <key>Apple</key>
    <true/>
    <key>uuid</key>
    <string>uuidVariable</string>
</dict>

<dict>
    <key>Banana</key>
    <false/>
    <key>uuid</key>
    <string>uuidVariable</string>
</dict>

I'm able to generate a UUID and store it :

UUID=$(cat /proc/sys/kernel/random/uuid) 

But how is it possible to loop through myfile.xml and replace each string with a new UUID?

I know how to count the occurring string, but i don't think this is gonna help me further

countUUID=$(sed 's/uuidVariable/uuidVariable\n/g' myfile.xml | grep -c "uuidVariable")

EDIT: Also i know how to replace 2 strings.. but thats not solving the problem having each unique.

sed -i s/uuidVariable/UUID/g myfile.xml
samecat
  • 335
  • 1
  • 11

2 Answers2

3

I suppose you could do something like this.

awk 'BEGIN { p="/proc/sys/kernel/random/uuid" }
    /uuidVariable/ { getline uuid < p; close(p)
        sub("uuidVariable", uuid) } 1' file.xml >newfile.xml
tripleee
  • 175,061
  • 34
  • 275
  • 318
0

Without external utilities, using parameter expansion:

#!/usr/bin/env bash

source=/proc/sys/kernel/random/uuid

while IFS= read -r line; do
    printf '%s\n' "${line//uuidVariable/$(<"$source")}"
done < input > output

Note that this solution will be slow for large input files. Some further reading:

PesaThe
  • 7,259
  • 1
  • 19
  • 43