Problem

Given a text file file.txt, transpose its content.

You may assume that each row has the same number of columns, and each field is separated by the ' ' character.

Examples

Example:

If file.txt has the following content:

1
2
3
name age
alice 21
ryan 30

Output the following:

1
2
name alice ryan
age 21 30

Solution

Intuition

awk can process each field and store them by column, then print each column as a row.

Approach

Read each line, store each field in an array by column, then print the columns as rows at the end.

Code

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

Complexity

  • ⏰ Time: O(n*m) where n is the number of rows and m is the number of columns.
  • 🧺 Space: O(n*m)

Method 2 – Using Bash Arrays

Intuition

Read all lines, split into words, and reconstruct by columns.

Approach

Read the file into an array, then for each column, print the corresponding field from each row.

Code

1
2
3
4
5
6
7
8
while read -a line; do
    for i in "${!line[@]}"; do
        a[$i]="${a[$i]} ${line[$i]}"
    done
done < file.txt
for i in "${!a[@]}"; do
    echo ${a[$i]}
done

Complexity

  • ⏰ Time: O(n*m)
  • 🧺 Space: O(n*m)