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.

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

name age
alice 21
ryan 30

Output the following:

name alice ryan
age 21 30

思路:相当于矩阵转置

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
转置一个文件,每个单词空格隔开看做是矩阵中的一个元素,然后将转置后的内容打印出来。

awk关键字的做法:NF表示当前记录中的字段个数,就是有多少列,NR表示已经读出的记录数,就是行号,从1开始,是个变量。那么在这里NF是2,因为文本只有两列,这里面这个for循环i实际上遍历的数字为1,2,1,2,1,2。

(NF表示总列数,$1表示第一列的值)

遍历过程如下:
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]
然后我们再将s中的各行打印出来即可。

你可能感兴趣的:(LeetCode)