Skip to main content
Bash and Linux

Transpose a File

mediumawk and cut

Problem statement

Turn the rows of a space-separated table into columns, so the first column becomes the first row. It is a classic awk exercise that teaches how to store values while reading and print them in a different shape at the end, which you need whenever a tool gives you data sideways.

file.txt

TEXT
name age city
asha 31 pune
ravi 27 delhi

Print the table transposed: line 1 holds the first column, line 2 the second column, and so on.

Expected output:

TEXT
name asha ravi
age 31 27
city pune delhi

Hints

Hint 1: While reading, build one text string per column number: row[i] holds everything seen so far in column i.

Approach

Optimal: Build each output row

Covers: awk loops for (i = 1; i <= NF; i++), $i, string joining, arrays keyed by number, tracking the widest line, END.

Read across, print down. In the input, each line is a row. In the output, each column must become a row. awk reads one line at a time, so it cannot print the result until it has seen every line. The plan:

%%{init: {"flowchart": {"padding": 18, "nodeSpacing": 30, "rankSpacing": 40, "htmlLabels": true}, "themeVariables": {"fontSize": "18px"}}}%% flowchart LR subgraph IN["file.txt: rows"] direction TB I1["name age city"]:::blue ~~~ I2["asha 31 pune"]:::blue ~~~ I3["ravi 27 delhi"]:::blue end subgraph OUT["output: columns become rows"] direction TB O1["name asha ravi"]:::green ~~~ O2["age 31 27"]:::green ~~~ O3["city pune delhi"]:::green end IN --> OUT classDef blue fill:#dbeafe,stroke:#2563eb,color:#1e3a8a,stroke-width:2px classDef yellow fill:#fef3c7,stroke:#d97706,color:#78350f,stroke-width:2px classDef green fill:#d1fae5,stroke:#059669,color:#064e3b,stroke-width:2px classDef red fill:#fee2e2,stroke:#dc2626,color:#7f1d1d,stroke-width:2px classDef purple fill:#ede9fe,stroke:#7c3aed,color:#4c1d95,stroke-width:2px classDef gray fill:#f3f4f6,stroke:#6b7280,color:#111827,stroke-width:2px linkStyle default stroke:#94a3b8,stroke-width:2px style IN fill:transparent,stroke:#2563eb,stroke-width:2px style OUT fill:transparent,stroke:#059669,stroke-width:2px
  1. Keep one growing piece of text for every column number: row[1], row[2], row[3].
  2. For each line, visit every field with a loop and add it to the matching row[i].
  3. After the last line, print row[1], then row[2], and so on.

Looping over fields. for (i = 1; i <= NF; i++) runs once for every field on the line: i starts at 1, goes up by 1, and stops after NF. Inside, $i is "field number i", so the same code works for any number of columns.

Joining text. In awk, writing two values side by side joins them: row[i] " " $i is the old text, a space, and the new field. The first line has no old text, so it stores $i alone; otherwise every row would start with a space.

After line row[1] row[2] row[3]
1 name age city
2 name asha age 31 city pune
3 name asha ravi age 31 27 city pune delhi

Why track max? If one line has more fields than the first, the number of output rows must follow the widest line. if (NF > max) max = NF remembers it, and the END loop runs up to max.

Walking through the code. The # Setup: lines only create the sample file, so skip past them. The awk program builds row[i] as shown in the table, then the END block prints the rows in order.

Edge cases. The whole table is kept in memory, so a huge file needs as much memory as its size. If a later line is shorter, its missing cells are simply left out, which shifts values; real data should be checked for equal widths first. An empty file prints nothing.

# Setup: create the sample table in a fresh temporary folder
cd "$(mktemp -d)"
cat > file.txt << 'DATA'
name age city
asha 31 pune
ravi 27 delhi
DATA

awk '
  {
    for (i = 1; i <= NF; i++) {
      if (NR == 1) row[i] = $i            # first line: start each output row
      else         row[i] = row[i] " " $i # later lines: add a space and the value
    }
    if (NF > max) max = NF                # remember the widest line
  }
  END {
    for (i = 1; i <= max; i++) print row[i]
  }
' file.txt

Interview follow-ups

  • Rows have different lengths. Fill missing cells with a dash.

    Store cells by row and column number instead of joining as you go: cell[NR, i] = $i, and track the widest line in max. In END, loop i from 1 to max and, inside, r from 1 to NR, printing cell[r, i] or - when (r, i) in cell is false. This keeps every column aligned even when some lines are short.

Frequently asked questions

Not in the standard set. Some systems have datamash transpose or rs -T, but they are extra packages that many servers do not have. For quick work, column -t lines up columns nicely but does not swap them. That is why interviews and the LeetCode version expect the awk answer: it works on any Linux box.

Tell awk the input separator and use the same one when joining: awk -F, '{ for (i = 1; i <= NF; i++) row[i] = (NR == 1 ? $i : row[i] "," $i) } END { for (i = 1; i in row; i++) print row[i] }' data.csv. The ? : picks between the two cases in one line. As with cut, quoted fields that contain commas need a real CSV tool.

You could run cut -d' ' -f1 file.txt | paste -sd' ' - once for each column number. That reads the whole file once per column, so a table with 50 columns is read 50 times. The awk version reads it once. For a three-column file it does not matter, but the habit of one pass is worth having.