HomeLeetcode194. Transpose File - Leetcode Solutions

194. Transpose File – Leetcode Solutions

Description

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:

name age
alice 21
ryan 30
Output the following:

name alice ryan
age 21 30

Solution in Bash

Bash
awk '
{
    for (i = 1; i <= NF; i++) {
        if (NR == 1) {
            transposed[i] = $i
        } else {
            transposed[i] = transposed[i] " " $i
        }
    }
}
END {
    for (i = 1; i <= NF; i++) {
        print transposed[i]
    }
}
' file.txt

Explanation

  • awk processes the file line by line.
  • NF is a built-in awk variable that represents the number of fields in the current record (line).
  • NR is a built-in awk variable that represents the current record number (line number).
  • The script builds the transposed content by appending the current field to the corresponding element in the transposed array.
  • After processing all lines, it prints the transposed content by iterating over the transposed array.

This will transpose the rows and columns, producing the desired output.

Subscribe
Notify of

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments

Popular