Saturday, November 8, 2014

Dynamically building AWK statements w/eval

E.g. This will sum the column entries entered on the command line

#!/bin/bash
eval "awk '{print $(echo "${*:2}" | sed -r 's/\b[0-9]*\b/\$&+/g;s/\+$//')}' $1" 
E.g. cat num.txt
5 4 3 2 1
5 4 3 2 1
5 4 3 2 1
5 4 3 2 1
5 4 3 2 1
5 4 3 2 1
5 4 3 2 1
5 4 3 2 1
5 4 3 2 1
5 4 3 2 1

$>my.awk num.txt 2 3
7
7
7
7
7
7
7
7
7
7 

No comments:

Post a Comment