tags:

views:

98

answers:

3

So here is my problem. How can I extract those strings into 3 variables with a bash script?

So out of this:

<key>GameDir</key> <string>C:/Program Files/</string> <key>GameEXE</key> <string>C:/Program Files/any.exe</string> <key>GameFlags</key> <string>-anyflag</string>

I want:

GameDir=C:/Program Files/
GameEXE=C:/Program Files/any.exe
GameFlags=-anyflag

Example Script:

echo GameDir
echo GameEXE
echo GameFlags

Example Output:

C:/Program Files/
C:/Program Files/any.exe
-anyflag

The order of the keys is not changing, only the strings itself. I am using OS X, so it needs to be a command that works out-of-the-box on OS X. Maybe this could work with sed?

Thanks Drakulix

A: 
echo yourstring|sed -e 's/<key>//g' -e 's/<\/key>\s*<string>/=/g' -e 's/<\/string>\s*/\n/g'
Adam Schmideg
A: 

Assuming Bash version >= 3.2

string='<key>GameDir</key> <string>C:/Program Files/</string> <key>GameEXE</key> <string>C:/Program Files/any.exe</string> <key>GameFlags</key> <string>-anyflag</string>'

or

string=$(<file)

and

pattern='<key>([^<]*)</key>[[:blank:]]*<string>([^<]*)</string>[[:blank:]]*'
pattern=$pattern$pattern$pattern
[[ $string =~ $pattern ]]    # extract the matches into ${BASH_REMATCH[@]}
for ((i=1; i<${#BASH_REMATCH[@]}; i+=2))
do
    declare ${BASH_REMATCH[i]}="${BASH_REMATCH[i+1]}"    # make the assignments
done
echo $GameDir    # these were missing dollar signs in your question
echo $GameEXE
echo $GameFlags
Dennis Williamson
Now it works.Great!Big THX!
Drakulix
@Drakulix: I'm glad that it works. You can mark the answer as accepted.
Dennis Williamson
A: 

you can use awk, this works for multiline and multiple key, string values.

$ cat file
<key>GameDir</key> <string>C:/Program Files/
   </string>
<key>GameEXE</key>
  <string>C:/Program Files/any.exe
 </string> <key>GameFlags</key> <string>-anyflag</string>

$ awk -vRS="</string>" '/<key>/{gsub(/<key>|<string>|\n| +/,"") ; sub("</key>","=") ;print}' file
GameDir=C:/ProgramFiles/
GameEXE=C:/ProgramFiles/any.exe
GameFlags=-anyflag

Use eval to create the variables

$ eval $(awk -vRS="</string>" '/<key>/{gsub(/<key>|<string>|\n| +/,"") ; sub("</key>","=") ;print}' file )
$ echo $GameDir
C:/ProgramFiles/
ghostdog74