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.
Example:
If file.txt has the following content:
name age alice 21 ryan 30
Output the following:
name alice ryan age 21 30
The goal of #194 Transpose File is to transform rows of a text file into columns. Each row contains space-separated values, and the output should print the first column of every row as the first row, the second column as the second row, and so on. In other words, you are performing a matrix transpose operation using Shell tools.
A common strategy is to process the file using awk. As the file is read line by line, you can store values based on their row and column indices. By tracking the maximum number of fields (NF) encountered, you ensure that all columns are handled correctly. After reading the entire input, iterate through the stored structure column by column and print the values in the required order.
This approach works well because awk naturally supports field-based parsing and associative arrays. The algorithm essentially visits every element once while storing intermediate results. The overall time complexity is proportional to the number of elements in the file, while the space complexity depends on how many entries must be temporarily stored during processing.
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| AWK-based matrix transpose | O(m × n) | O(m × n) |
Sahil & Sarra
Watch expert explanations and walkthroughs
Jot down your thoughts, approach, and key learnings
Yes, but awk is the most convenient tool for field-based text processing in Shell. Alternatives like sed, cut, or pure bash loops can be used, though they tend to be more complex and less readable.
Problems like Transpose File are occasionally used to test practical scripting and text-processing skills. While not always asked directly, understanding tools like awk and handling structured text is valuable in system and DevOps-style interview questions.
Associative arrays in awk are commonly used because they allow indexing by row and column positions. This makes it easy to reconstruct the matrix in a transposed format during the output phase.
The most common approach uses awk to parse the file and treat each row as fields. Values are stored using row and column indices, and then printed column by column to produce the transposed output. This efficiently processes the entire file in a single pass.