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

1 comment:

Unknown said...



_ord() {
printf '%d\n' "'$1"
}
q=${1:-"'"}
if='/tmp/file.txt'


## Dc
< $if perl -F\: -pale '$_ = join $", map { "[$_]" } @F' |
dc -e "
[q]sq [$(_ord "$q")a]sQ [32a]sS
[sx]sa
[z 2 <a z 2 <b]sb
[
[Top in]n lSxn
lQxn rn lQxn
lSxn 58an lSxn
lQxn n lQxn
[]p
]sp
[? z 0 =q lbx lpx c l?x]s?
l?x
"


## Sed
eval "`echo 'NL=qtq' | tr 'qt' '\047\012'`"
# escape $q to be acceptable to sed in the RHS of s///
case $q in "$NL" | '\' | '/' ) Eq="\\$q";; * ) Eq=$q;; esac
< $if sed -e "
s/:/\n/2; s/\n.*//
s/:/$Eq : $Eq/; s/.*/Top in $Eq&$Eq/
"

## Perl
< $if perl -F\: -spale '
$_ = join $", (q{Top in}, map("$q$_$q",@F[0,1]), q(:))[0,1,3,2];
' -- -q="$q"


## Bash
while IFS= read -r line
do
IFS=':'; set -f; set -- $line
printf 'Top in %s : %s\n' "$q$1$q" "$q$2$q"
done < $if

© Jadu Saikia www.UNIXCL.com