leetcode-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:

1
2
3
name age
alice 21
ryan 30

Output the following:

1
2
name alice ryan
age 21 30

解决方案


依旧是强大的 Awk。NR 是 Awk 的内建变量,表明目前读到的行号,NF 也是 Awk 的内建变量,记录当前行的字段数量。

1
2
3
4
5
6
# Read from the file file.txt and print its transposed content to stdout.
awk '
NR == 1 { for (i = 1; i <= NF; i++) { line[i] = $i } }
NR > 1 { for (i = 1; i <= NF; i++) { line[i] = line[i] " " $i } }
END { for (i = 1; i <= NF; i++) { print line[i] } }
' file.txt

题目来源