Home > Net >  Use awk to repeat first column in CSV with unknown amount of columns
Use awk to repeat first column in CSV with unknown amount of columns

Time:11-30

I'm trying to create a 2 column CSV, where the first column is a name, and the second column is the value. I am able to do this with a nested loop, but I'm positive that AWK can do this much faster

DATA='POLICY_NAME01,VM001,VM002,VM003
POLICY_NAME02,VM004
POLICY_NAME03,VM005,VM006'

IFS=$'\n'
for LINE in $DATA; do
    POLICY=$(echo "${LINE}" | cut -d , -f 1)
    VMS=$(echo "${LINE}" | cut -d , -f 2- | tr ',' '\n')
    for VM in $VMS; do
        echo "${POLICY},${VM}"
    done
done

OUTPUT:

POLICY_NAME01,VM001
POLICY_NAME01,VM002
POLICY_NAME01,VM003
POLICY_NAME02,VM004
POLICY_NAME03,VM005
POLICY_NAME03,VM006

CodePudding user response:

This awk should work:

awk 'BEGIN{FS=OFS=","} {for (i=2; i<=NF;   i) print $1, $i}' <<< "$DATA"

POLICY_NAME01,VM001
POLICY_NAME01,VM002
POLICY_NAME01,VM003
POLICY_NAME02,VM004
POLICY_NAME03,VM005
POLICY_NAME03,VM006
  • Related