开发者

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 outp开发者_StackOverflowut:

A
A
A
B
B
B
C
C
C


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


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


Try:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜