Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading