194. Transpose File
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
From: LeetCode
Link: 194. Transpose File
Solution:
Ideas:
-
Reading lines and columns: awk processes the file line by line. For each field in the line, it appends the field to the corresponding index in the transposed array.
-
Constructing the transposed lines: As we read each line, we concatenate the fields to build the transposed rows. The NR variable tracks the line number.
-
Printing the transposed result: After processing all lines (END block), we print each element of the transposed array.
Code:
# Read from the file file.txt and print its transposed content to stdout.
awk '
{
for (i = 1; i <= NF; i++) {
if (NR == 1) {
transposed[i] = $i
} else {
transposed[i] = transposed[i] " " $i
}
}
}
END {
for (i = 1; i <= NF; i++) {
print transposed[i]
}
}' file.txt
标签:transposed,File,194,Transpose,file,each,line,txt
From: https://blog.csdn.net/navicheung/article/details/140090780