0

I have a file with an indeterminate amount of columns, split by a ~ character, like so:

1~5~4
toast~8~test
3~9~8

How would I loop through each column, and move it to the bottom? I want the output to be:

1
toast
3
5
8
9
4
test
8

I know you would need to identify the number of columns, but I'm not quite sure how to do this, and then loop through and move them.

2 Answers 2

1

You can do it in two steps using the rs (reshape) utility

  1. first transpose, using ~ as the column delimiter
  2. then reshape into a single column

Ex.

$ rs -c~ -T < file | rs 0 1
1
toast
3
5
8
9
4
test
8

Alternatively, with Awk:

$ awk -F~ '
    {for (i=1;i<=NF;i++) a[i] = a[i] == "" ? $i : a[i] "\n" $i} 
    END {for (i in a) print a[i]}
  ' file
1
toast
3
5
8
9
4
test
8
0
$ perl -F'~' -lane '
    $A[$_][$.-1] = $F[$_] for 0 .. $#F;}{
    print join $/, @{$A[$_]} for 0 .. $#A;
' input.file

Collect and store columns in a multi dimensional array such that first index refers to column number and second to line number. Then at the end loop over the col num and print each array element separated by newline.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .