Question

Formatted question description: https://leetcode.ca/all/194.html

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.

For example, if file.txt has the following content:

name age
alice 21
ryan 30
 

Output the following:

name alice ryan
age 21 30

Algorithm

Usually we think that i can only be 1 and 2, and then the loop ends.

And the number i actually traversed here is 1, 2, 1, 2, and 1, we may see that it actually circulates 3 times 1 and 2, and the number of rows is exactly 3. Maybe this is the mechanism.

Knowing the above, then the following code is not difficult to understand, the traversal process is as follows:

i = 1, s = [name] i = 2, s = [name; age]

i = 1, s = [name alice; age] i = 2, s = [name alice; age 21]

i = 1, s = [name alice ryan; age 21] i = 2, s = [name alice ryan; age 21 30]

Code

Shell

# NF represents the number of fields in the current record, that is, how many columns are there
# NR indicates the number of records that have been read, which is the line number
awk '{
    for (i = 1; i <= NF; ++i) {
        if (NR == 1) s[i] = $i;
        else s[i] = s[i] " " $i;
    }
} END {
    for (i = 1; s[i] != ""; ++i) {
        print s[i];
    }
}' file.txt

All Problems

All Solutions