Miles
Miles

Reputation: 23

In a *nix environment, how would I group columns together?

I have the following text file:

A,B,C
A,B,C
A,B,C

Is there a way, using standard *nix tools (cut, grep, awk, sed, etc), to process such a text file and get the following output:

A
A
A
B
B
B
C
C
C

Upvotes: 2

Views: 109

Answers (3)

Kurt Stutsman
Kurt Stutsman

Reputation: 4034

You could use a shell for-loop combined with cut if you know in advanced the number of columns. Here is an example using bash syntax:

for i in {1..3}; do
    cut -d, -f $i file.txt
done

Upvotes: 3

imm
imm

Reputation: 5919

Try:

awk 'BEGIN {FS=","} /([A-C],)+([A-C])?/ {for (i=1;i<=NF;i++) print $i}' YOURFILE | sort

Upvotes: 0

Foo Bah
Foo Bah

Reputation: 26271

You can do:

tr , \\n

and that will generate

A
B
C
A
B
C
A
B
C

which you could sort.

Unless you want to pull the first column then second then third, in which case you want something like:

awk -F, '{for(i=1;i<=NF;++i) print i, $i}' | sort -sk1 | awk '{print $2}'

To explain this, the first part generates

1 A
2 B
3 C
1 A
2 B
3 C
1 A
2 B
3 C    

the second part will stably sort (so the internal order is preserved)

1 A
1 A
1 A
2 B
2 B
2 B
3 C
3 C
3 C    

and the third part will strip the numbers

Upvotes: 5

Related Questions