Thursday, May 15, 2008

Sort and Add Prefix - BASH newbie


Suppose the input file 01.txt contains some numbers in random order.

$ cat 01.txt

4
50
3
1
8
2

Output Required: (A single line with all the numbers sorted and with a prefix age=)
--------------------
age=1,age=2,age=3,age=4,age=8,age=50

AWK solution:
------------------
$ sort -n 01.txt | awk '{print "age="$0}' | tr '\n' ',' | awk '{sub(/,$/,"");print}'

SED solution:
---------------------
$ sort -n 01.txt | sed 's/[0-9].*/age=&,/' | tr -d "\n" | sed 's/,$//'

Things to learn from above:
--------------------------------
1) use of & with sed.
2) use of tr command
3) awk sub function

No comments:

© Jadu Saikia www.UNIXCL.com