Transpose File

Shell
https://leetcode.com/problems/transpose-file

# Solution

# Iteration

ncol=`head -n 1 file.txt | wc -w`
for i in `seq $ncol`
do
cut -d ' ' -f $i file.txt | xargs
done
1
2
3
4
5

# Using xargs

head -n 1 file.txt | wc -w | xargs seq | xargs -n 1 -I {} sh -c "cut -d' ' -f {} file.txt | xargs"
1

# Using awk

See more on this LeetCode post (opens new window).

awk '
{
    for (i=1; i<=NF; i++) {
        if (FNR == 1) {
            arr[i] = $i;
        } else {
            arr[i] = arr[i] " " $i
        }
    }
}
END {
    for (i=1; arr[i]!=""; i++) {
        print arr[i]
    }
}
' file.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16