shell - Linux script sort and group without separator -
input given :
10001123 20001234 30002111 40003111 50004000 requirement:
sort character 2 5
group character 2 5
sum character 6 8
display line character 6 8 > 0
expected output given :
10001357 30002111 40003111
$ sed -r 's/(.)(....)(...)/\1 \2 \3/' file | awk '{if (!($2 in a))a[$2]=$1; b[$2]+=$3;} end{for (i in b) if (b[i]>0)print a[i],i,b[i];}' | sort -nk2 | sed 's/ //g' 10001357 30002111 40003111 how works
let's break command parts.
first sed command separates our groups spaces:
$ sed -r 's/(.)(....)(...)/\1 \2 \3/' file 1 0001 123 2 0001 234 3 0002 111 4 0003 111 5 0004 000 the second part awk summing:
awk '{if (!($2 in a))a[$2]=$1; b[$2]+=$3;} end{for (i in b) if (b[i]>0)print a[i],i,b[i];}' the output of awk looks like:
1 0001 357 3 0002 111 4 0003 111 next sort makes sure our output in desired order:
sort -nk2 lastly, use sed remove spaces added:
sed 's/ //g' note have been done awk. have broken input line parts substr. plain awk, have needed write our own sorting routine or, if gnu awk available, have used builtin sort routine, asort.
Comments
Post a Comment