Algorithms, Blockchain and Cloud

Linux BASH Coding Exercise – Transpose File


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.

For example, if file.txt has the following content:

name age
alice 21
ryan 30

Output the following:

name alice ryan
age 21 30

Submit your solution to: https://leetcode.com/problems/transpose-file/

Pure BASH solution

1
2
3
4
5
6
7
8
9
10
11
#!/bin/bash
 
while read -a line; do
    for ((i=0; i < "${#line[@]}"; i++)); do
        a[$i]="${a[$i]} ${line[$i]}"
    done
done < file.txt
 
for ((i=0; i < ${#a[@]}; i++)); do
    echo ${a[i]}
done
#!/bin/bash

while read -a line; do
    for ((i=0; i < "${#line[@]}"; i++)); do
        a[$i]="${a[$i]} ${line[$i]}"
    done
done < file.txt

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

This gets accepted by Online Judge - in - 384ms.

AWK solution

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

This is almost 10 times faster than pure bash solution above - 28ms!

The same algorithm, using for to transpose the matrix (stored in array of lines). However, awk is faster than pure interpreted BASH script.

--EOF (The Ultimate Computing & Technology Blog) --

256 words
Last Post: How to Convert Arabic Numerals (Integers) to English Words (C/C++ Solution)?
Next Post: C++ Coding Exercise - First Bad Version

The Permanent URL is: Linux BASH Coding Exercise – Transpose File (AMP Version)

Exit mobile version