Transpose a File
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
name age cityasha 31 puneravi 27 delhiPrint the table transposed: line 1 holds the first column, line 2 the second column, and so on.
Expected output:
name asha raviage 31 27city pune delhiHints
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:
- Keep one growing piece of text for every column number:
row[1],row[2],row[3]. - For each line, visit every field with a loop and add it to the matching
row[i]. - After the last line, print
row[1], thenrow[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.txtInterview 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 inmax. InEND, loopifrom 1 tomaxand, inside,rfrom 1 toNR, printingcell[r, i]or-when(r, i) in cellis 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.