Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash shell scripting transpose rows and columns

I need help transposing a file that just simply has some numbers in them with rows and columns. I can't use awk shell or perl so it makes it kind of hard. I've been working on it for a couple of hours and can't get it working correctly. I tried a couple of other things but this is what I have right now. It runs, but it doesn't print out anything, so that leads me to conclude that something is wrong within my code. Also if you dont know by transpose if a file had :

1 2 3 
4 5 6 

... it would then print out

1 4
2 5
3 6

Here is my code:

if [ $# -gt 2 ]
then
  echo"System error">&2
exit 1

elif [[ $# -eq 2 && -e "$2" && -r "$2" ]]
then 
while read -a line; do
    for ((i=0; i < "${#line[@]}"; i++)); do
        a[$i]="${a[$i]} ${line[$i]}"
    done
done < $2

for ((i=0; i < ${#a[@]}; i++)); do
    echo ${a[i]}
done


fi

1 Answers

If possible use awk:

Source (file.txt):

1 2 3
4 5 6

Result:

1 4
2 5
3 6

Oneline awk sctript:

awk '{ for (i=1; i<=NF; i++) a[i]= (a[i]? a[i] FS $i: $i) } END{ for (i in a) print a[i] }' file.txt

It works same with

1 2 3         1 4 7
4 5 6    ->   2 5
7             3 6

and with

1 2 3 4       1 5
5 6 7    ->   2 6
              3 7
              4
like image 173
Šerg Avatar answered Mar 22 '26 02:03

Šerg