An efficient way to transpose a file in Bash

前端 未结 29 2493
时光说笑
时光说笑 2020-11-22 03:30

I have a huge tab-separated file formatted like this

X column1 column2 column3
row1 0 1 2
row2 3 4 5
row3 6 7 8
row4 9 10 11

I would like t

29条回答
  •  萌比男神i
    2020-11-22 03:49

    Another option is to use rs:

    rs -c' ' -C' ' -T
    

    -c changes the input column separator, -C changes the output column separator, and -T transposes rows and columns. Do not use -t instead of -T, because it uses an automatically calculated number of rows and columns that is not usually correct. rs, which is named after the reshape function in APL, comes with BSDs and OS X, but it should be available from package managers on other platforms.

    A second option is to use Ruby:

    ruby -e'puts readlines.map(&:split).transpose.map{|x|x*" "}'
    

    A third option is to use jq:

    jq -R .|jq -sr 'map(./" ")|transpose|map(join(" "))[]'
    

    jq -R . prints each input line as a JSON string literal, -s (--slurp) creates an array for the input lines after parsing each line as JSON, and -r (--raw-output) outputs the contents of strings instead of JSON string literals. The / operator is overloaded to split strings.

提交回复
热议问题