How to Use AWK to Transpose Columns to Rows
You can use AWK to transpose a text table by storing each field under its input row and column number, then printing those stored fields column by column. For a simple one-column task, AWK can also join just $1, $2, or another selected field into one output row. The right command depends on whether you need a full matrix transpose, one chosen column, or complete input lines joined horizontally.
What Transposing Means in AWK
A transpose swaps the orientation of a table:
- Each input row becomes an output column.
- Each input column becomes an output row.
For example, this whitespace-separated input:
red green blue
circle square triangle
small medium large
becomes:
red circle small
green square medium
blue triangle large
AWK reads input one record at a time. By default, a record is one input line:
NRis the current input record number.NFis the number of fields on the current line.$1,$2, and so on are individual fields.$0is the complete current input line.
A full transpose cannot normally print its first output row until AWK has read all input rows, because it needs to know how many fields occur in the widest row.
How to Transpose a Full Text Table With AWK
Choose the command that matches the shape and delimiter of your data.
| Input and desired result | Use this approach |
|---|---|
| Whitespace-separated table; shorter rows may simply end early | Store fields by NR and field number, then print by field number |
| Tab-separated table where output blank positions matter | Set the input and output separators to tabs |
| One selected input column should become one row | Print $1, $2, or another chosen field with printf |
| Each entire input line should become part of one row | Print $0 with printf |
| Every individual field should become its own line | Loop from field 1 through NF and print each field |
Step 1: Confirm That Whitespace Splitting Is Safe
Use the standard full-table command when spaces or tabs are only separators and values themselves do not contain spaces.
For example, this is suitable input:
field1 field2 field3
field1 field2
field1
field1 field2 field3 field4
It is not suitable for data such as this, because New York would be split into two fields:
Name City
Avery New York
If your data is comma-separated, tab-separated, or includes quoted values, identify its real delimiter before running a transpose.
Step 2: Run the Full Transpose Command
Use this command when every input field must become the corresponding row in the transposed output, including input records with different field counts:
awk '{
for (f = 1; f <= NF; f++)
a[NR, f] = $f
}
NF > nf { nf = NF }
END {
for (f = 1; f <= nf; f++)
for (r = 1; r <= NR; r++)
printf "%s", a[r, f] (r == NR ? RS : FS)
}' infile | tr -s " " " " | sed 's/^ //' > outfile
Replace infile and outfile with the input and output paths you want to use.
The command works in three stages:
a[NR, f] = $fsaves every field using a two-part array index: its input line number and its field number.NF > nf { nf = NF }remembers the largest number of fields found in any input row.- The
ENDblock prints the saved data only after AWK has reached the end of the file.
The first output loop is:
for (f = 1; f <= nf; f++)
It iterates through the original input columns, which become output rows.
Inside it, the nested loop is:
for (r = 1; r <= NR; r++)
It iterates through the original input records, which become fields across each output row.
The tr and sed commands clean up extra spaces produced where shorter input rows have no corresponding field. This produces a ragged text result: absent fields disappear instead of being represented by fixed empty positions.
Step 3: Inspect the Saved Output
Display the new file before using it in another command or importing it elsewhere:
cat outfile
For the uneven input shown earlier, the output is:
field1 field1 field1 field1
field2 field2 field2
field3 field3
field4
The transpose is complete once the output has the original columns in top-to-bottom order and the original rows in left-to-right order.
Other AWK Commands for Columns and Rows
A full transpose is often more work than the actual task requires. Use a smaller command when you only need to reshape one part of the input.
Put One Selected Column on One Output Row
To join the first input column into one space-separated output row, use:
awk '{ printf "%s ", $1 } END { print "" }' inputfile
For input like this:
alpha one
beta two
gamma three
the result is:
alpha beta gamma
Use the field number that matches the input column you want to join. For example, replace $1 with $2 to select the second input column:
awk '{ printf "%s ", $2 } END { print "" }' inputfile
This is useful for building a short argument list, a label row, or a space-separated value list. It is not a full table transpose because it ignores every field except the selected one.
Join Complete Input Records Into One Row
When each complete input line should be appended horizontally, use $0:
awk '{printf "%s ", $0} END {print ""}' input.txt > output.txt
Given:
build
test
deploy
the output is:
build test deploy
This preserves each record as a unit. It does not split the input into fields before joining it.
Write Every Field as Its Own Row
To flatten a whitespace-separated file so that every field becomes a separate output line, use:
awk '{for(i=1;i<=NF;i++) print $i}' input.txt > output.txt
For this input:
red green
blue yellow
the output is:
red
green
blue
yellow
This is a field-by-field flattening operation, not a transpose. It is useful when a downstream tool accepts one value per line.
Handle Tabs, CSV, and Missing Values Correctly
The separator you choose determines whether AWK can distinguish a real empty cell from a missing field.
Whitespace-separated input is convenient for logs and command output, but it is not a reliable table format when blank cells must retain their positions. AWK’s default whitespace splitting treats runs of spaces and tabs as separators, so it cannot tell whether several spaces represent formatting or empty columns.
Transpose a Tab-Separated File
For tab-separated data, set AWK’s field separator to a tab and print tabs in the result:
awk -F '\t' '{
if (NF > max)
max = NF
for (c = 1; c <= NF; c++)
cell[NR, c] = $c
}
END {
for (c = 1; c <= max; c++) {
for (r = 1; r <= NR; r++)
printf "%s%s", cell[r, c], (r == NR ? ORS : "\t")
}
}' input.tsv > output.tsv
This is the better choice when the output must remain a tabular file for a spreadsheet, database import, or another parser. Empty positions remain represented by adjacent tab separators in the output.
Do Not Treat Complex CSV as Plain Whitespace Data
A command such as awk -F ',' is only safe for simple CSV where commas cannot appear inside quoted values. Real CSV commonly allows values such as:
"Avery Smith","New York, NY"
For quoted CSV, use a CSV-aware parser to produce a safe delimiter format first, or use a tool with proper CSV parsing support. Then transpose the resulting tab-separated data.
Keep Headers Deliberately
A full transpose treats a header row exactly like every other row. For this input:
Name Team Score
Avery Blue 9
Jordan Green 7
the output begins with:
Name Avery Jordan
Team Blue Green
Score 9 7
That is often useful because field names become the first item in each output row. If you do not want headers in the result, remove or skip the header before transposing.
Verify That the Transpose Is Correct
Check the result before passing it to another script, especially when rows have inconsistent widths.
Use this quick checklist:
- The number of output rows should equal the greatest field count in the input.
- The first output row should contain the first field from every input line.
- The second output row should contain the second field from every input line.
- For tabular output with required blank cells, inspect the file with a tool that shows delimiters rather than relying only on visual spacing.
You can compare input and output side by side during testing:
paste infile outfile
For a small sample, manually verify the top-left values: input row 1, field 1 remains the first output value; input row 2, field 1 becomes the second value on the first output row.
Frequently Asked Questions
Can AWK transpose uneven rows?
Yes. The full-table command tracks the largest NF value found and prints a row for every possible field position. With whitespace-separated output and cleanup through tr -s " " " " plus sed 's/^ //', missing fields produce a shorter-looking output row rather than a visible placeholder.
How do I transpose only the second column with AWK?
Use $2 instead of $1 in a selected-column command:
awk '{ printf "%s ", $2 } END { print "" }' inputfile
$2 means the second whitespace-separated field on each input line. Choose another field number when the target column is different.
Can AWK transpose a CSV file?
AWK can transpose simple comma-delimited text, but plain comma splitting is unsafe when CSV values contain quoted commas, embedded newlines, or escaped quotes. Convert complex CSV to a reliably delimited format such as TSV with a CSV-aware tool, then transpose the tab-separated result.
Why does my output lose blank columns?
Whitespace is not a fixed-width table format to AWK. Default field splitting collapses separator runs, and the whitespace transpose command intentionally squeezes extra output spaces; use tabs when an empty field must remain in a specific column position.
Will a full AWK transpose work on a very large file?
A full AWK transpose may use substantial memory because AWK stores fields until it reaches the end of the input. A full transpose requires access to values from all rows before it can print each output row, so joining one column or one complete line at a time is a better option when you do not truly need a matrix transpose.
Make the Transpose Repeatable
Keep a small representative input file with your script and test it whenever the upstream format changes. Document whether the file is whitespace-separated, tab-separated, or CSV and whether blank fields are meaningful.
For recurring work, prefer tab-separated input and output when the data is genuinely tabular. Then run the transpose as part of the same pipeline that creates the file, inspect the resulting delimiter structure once, and feed the verified output to the next command.
