Wednesday, November 11, 2009

Printing single quote in awk - bash


Input file:

$ cat /tmp/file.txt
Computer programming:Zia:78
discrete mathematics:Nil:82
Quantum physics:Leni:91
biomedical engineering:Qureg:82
computer architecture:Anu:90

Required output:

Top in 'Computer programming' : 'Zia'
Top in 'discrete mathematics' : 'Nil'
Top in 'Quantum physics' : 'Leni'
Top in 'biomedical engineering' : 'Qureg'
Top in 'computer architecture' : 'Anu'

i.e.

Top in '1st field' : '2nd field'

Using awk variable assignment technique, i.e. assigning the value 'single quote' to the variable x below:

$ awk -F: -v x="'" '
{print "Top in",x$1x,":",x$2x}
' /tmp/file.txt

And to use "double-quote":

$ awk -F: -v x="\"" '
{print "Top in",x$1x,":",x$2x}
' /tmp/file.txt

Top in "Computer programming" : "Zia"
Top in "discrete mathematics" : "Nil"
Top in "Quantum physics" : "Leni"
Top in "biomedical engineering" : "Qureg"
Top in "computer architecture" : "Anu"

Another solution will be to use the ASCII for 'single colon':

$ awk -F: '
{print "Top in","\x27"$1"\x27",":","\x27"$2"\x27"}
' /tmp/file.txt

Since number of fields in the input file is very few, we can try this using 'sed'; something like:

$ sed "
s_\(.*\):\(.*\):\(.*\)_Top in '\1' : '\2'_g
" /tmp/file.txt

Above, as you can see I am using underscore symbol in place of common slash "/" (just to avoid confusion)

Related posts:

- Print a column using UNIX sed
- How to access external variable in awk and sed

No comments:

© Jadu Saikia www.UNIXCL.com