Transpose File Problem
#194
Description
LeetCode Problem 194.
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
Solution
Approach: Build one output line per column
Read the file row by row and grow one string per column: field i of every input row is appended to string i. After the last row, the strings are the rows of the transposed file.
- For the first row (
NR == 1) the string is just the field; for later rows it is the previous string, a space, then the field. That avoids a stray leading space. - All rows have the same number of columns, so in the
ENDblockNFstill holds the column count of the last row and tells us how many lines to print.
# Print the transpose of file.txt.
awk '
{
for (i = 1; i <= NF; i++) {
if (NR == 1) {
res[i] = $i
} else {
res[i] = res[i] " " $i
}
}
}
END {
for (i = 1; i <= NF; i++) {
print res[i]
}
}
' file.txt