Parse Simple XML Files using Bash – Extract Name Value Pairs and Attributes

I have written up a simple routine parseXML to parse simple XML files to extract unique name values pairs and their attributes. The script extracts all xml tags of the format <abc arg1="hello">xyz</abc> and dynamically creates bash variables which hold values of the attributes as well as the elements. This is a good solution, if you don’t wish to use xpath for some simple xml files. However you will need xmllint installed on your system to use the script. Here’s a sample script which uses the parseXML function Continue reading

Custom Key Bindings / Keyboard Shortcuts in Bash

Bash is so powerful that you can keep digging and finding out newer secrets all the time. We already use bash keyboard bindings – Ctrl d to exit the terminal, Ctrl r for reverse search and so on. Now won’t it be convenient if you could assign keyboard bindings to commands of your choice, to execute them quickly or just to insert lengthy commands which you use repeatedly with subtle changes. Lets look at an example. Continue reading

Pass Bash Variables to Awk

Bash variables can’t be passed into awk, like one can with a lot of other commands. They need to be declared using the -v option. Here’s a code snippet which shows how.

awk -v a="$mainstring" -v b="$substring" 'BEGIN  { print index(a,b) }'

The above awk command is for locating the position of the first letter of the substring cde within the main string abcdef. In this case the position is 3, which is the position of the character ‘c’ in the main string. The variables $mainstring and $substring are passed into awk by pre-declaring them as a and b respectively.