ISO logoISO logo

The other day I needed to create a list of ISO3166 language codes in the following format: ‘XX’,’YY’,’ZZ’. Being lazy, and also a fan of performing a bit of bash oneliner magic, or oneliner golf as some refer to it, I decided to take a stab at it. After a short while, I ended up with the following code:

xmllint --noout --xpath '//iso_3166_entry/@*[name() = "alpha_2_code"]' /usr/share/xml/iso-codes/iso_3166.xml | sed 's/alpha_2/\nalpha_2/g' | awk -F'"' 'OFS="," {if ($2) print "\047"$2}' | awk '/START/{if (x)print x;x="";}{x=(!x)?$0:x","$0;}END{print x "\047";}'

If you would want the following format: XX,YY,ZZ, then use the following:

xmllint --noout --xpath '//iso_3166_entry/@*[name() = "alpha_2_code"]' /usr/share/xml/iso-codes/iso_3166.xml | sed 's/alpha_2/\nalpha_2/g' | awk -F'"' 'OFS="," {if ($2) print $2}' | awk '/START/{if (x)print x;x="";}{x=(!x)?$0:x","$0;}END{print x;}'

If you would want them each on their own line, then use the following:

xmllint --noout --xpath '//iso_3166_entry/@*[name() = "alpha_2_code"]' /usr/share/xml/iso-codes/iso_3166.xml | sed 's/alpha_2/\nalpha_2/g' | awk -F'"' 'OFS="," {if ($2) print $2}'

Completely useless and pointless for most of you, but for me a bit of fun to distract the mind.

By Jostein Elvaker Haande

"A free society is a society where it is safe to be unpopular" - Adlai Stevenson

Leave a Reply

Your email address will not be published. Required fields are marked *