Saturday, May 23, 2015

awk: split string into array and select an array element

Say the input is a character string with varying number of comma separated elements, eg,, 
ABC,DEF,GHI,JKL,MNO

If we want to the extract the second last element in this string (i.e., JKL)
echo ABC,DEF,GHI,JKL,MNO  | awk '{len=split($0,arr,","); print arr[len-1]}'

where the variable len is used to capture the length of the array created by split. Therefore, to print the array length,
echo ABC,DEF,GHI,JKL,MNO  | awk '{len=split($0,arr,","); print len}'