Format vertically maintaining first column

2

It's been a long time since I've used grep or sed but I think this can be done. How do I take a csv and format it vertically while maintaining/replicating the first columns.

Ex.
Input:
A, 1, 2, 3
B, 1, 2, 3
C, 1, 2, 3

Output:
A, 1
A, 2
A, 3
B, 1
B, 2
B, 3
C, 1
C, 2
C, 3

Steve Zemlicka

Posted 2018-01-04T23:56:21.547

Reputation: 21

Answers

2

You could do it with sed, or maybe some versions of grep, however, using awk you can very elegantly express what you want to accomplish:

#!/bin/sh

awk -F, '
    BEGIN {
        OFS=","
    }
    {
        for (i=2; i<=NF; i++) {
            print $1, $i
        }
    }
' <<EOF
A, 1, 2, 3
B, 1, 2, 3
C, 1, 2, 3
EOF

If you want the script to take filenames or standard input, replace the "here document" (everything from the << to the end of the file) with:

"$@"

RobertL

Posted 2018-01-04T23:56:21.547

Reputation: 339

1

A sed solution.

sed -r ':a;s/([A-Z],)( [0-9]),( [0-9])/\1\2\n\1\3/;ta' <<<'A, 1, 2, 3
B, 1, 2, 3
C, 1, 2, 3'
A, 1
A, 2
A, 3
B, 1
B, 2
B, 3
C, 1
C, 2
C, 3

Paulo

Posted 2018-01-04T23:56:21.547

Reputation: 606