Monday, April 6, 2009

Sum with awk substr function - bash


I have already explained about awk substr function , using which a sub string can be extracted from a string.
Lets see how we can use substr along with a normal awk sum operation.

e.g. In the below file, lets try to sum all the numbers starting from character position 6 till position 10 for all lines except lines starting with T and Y.

$ cat file.txt
A052K2500sle12t09
K094T1200sle12t09
T129K1000@5900xpt
R5k9T1600tkxp90st
A152Y2700kle12t08
Yp90w1256newrt900

The awk solution:

$ awk '/^[^TY]/ { s+=substr($0,6,4) }
END { printf("sum=(%d)\n",s) }' file.txt

Output:
sum=(8000)

Related post:
- Print characters before and after a pattern using awk
- Sort date in ddmmyyyy format using awk
- Change date format using awk

1 comment:

ubuntu said...

HI,
I liked your posts for bash commands. I recommend you to visit and register on http://www.commandlinefu.com/commands/browse

Here you can publish Unix commands and get them rated as well.

© Jadu Saikia www.UNIXCL.com