Transpose File - 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 ' ' (space) character.

For example: If file.txt has the content:

name age
john 33
mike 80

Your script should output:

name john mike
age 33 80

Note: This is a shell scripting problem that requires reading and processing file content line by line.

Input & Output

Example 1 — Basic Transpose
$ Input: name age\njohn 33\nmike 80
Output: name john mike\nage 33 80
💡 Note: First row becomes first column: 'name john mike'. Second row becomes second column: 'age 33 80'.
Example 2 — Three Columns
$ Input: a b c\n1 2 3\nx y z
Output: a 1 x\nb 2 y\nc 3 z
💡 Note: Column 1: a,1,x become row 1. Column 2: b,2,y become row 2. Column 3: c,3,z become row 3.
Example 3 — Two Rows Only
$ Input: hello world\nfoo bar
Output: hello foo\nworld bar
💡 Note: Transpose 2x2 matrix: first column 'hello foo', second column 'world bar'.

Constraints

  • Each row has the same number of columns
  • Fields are separated by single space character
  • No empty lines in input
  • Maximum 1000 rows and 100 columns

Visualization

Tap to expand
Transpose File - Shell AWK Solution INPUT file.txt: name age john 33 mike 80 Col 1 Col 2 Raw Input: name age john 33 mike 80 3 rows x 2 columns Space-separated values ALGORITHM STEPS 1 Read First Line Get column count (NF=2) 2 Build Result Array res[col] += $col for each row 3 Concatenate Values Append each col value to res 4 Print Transposed Output each res[i] as row Array Building: res[1] = "name" res[1] += " john" += " mike" res[2] = "age" res[2] += " 33" += " 80" AWK handles row-by-row FINAL RESULT Transposed output: name john mike age 33 80 Row 1 Row 2 Output: name john mike age 33 80 OK - Transposed! 2 rows x 3 columns Rows become columns Key Insight: AWK processes files line-by-line. We use an associative array where res[column_index] accumulates all values from that column across rows. After processing all lines, print each array element as a row. awk '{for(i=1;i<=NF;i++) res[i]=res[i]" "$i} END{for(i=1;i<=NF;i++) print substr(res[i],2)}' TutorialsPoint - Transpose File | Shell AWK Solution
Asked in
Google 25 Amazon 18 Microsoft 15
12.5K Views
Medium Frequency
~15 min Avg. Time
350 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen