Skip to content

Latest commit

 

History

History
65 lines (46 loc) · 1.23 KB

194-transpose-file.md

File metadata and controls

65 lines (46 loc) · 1.23 KB

194. Transpose File - 转置文件

给定一个文件 file.txt,转置它的内容。

你可以假设每行列数相同,并且每个字段由 ' ' 分隔.

示例:

假设 file.txt 文件内容如下:

name age
alice 21
ryan 30

应当输出:

name alice ryan
age 21 30

题目标签:

题目链接:LeetCode / LeetCode中国

题解

Language Runtime Memory
bash 16 ms N/A
# Read from the file file.txt and print its transposed content to stdout.

# using awk for this purpose
awk '
    {
        for(i=1; i<=NF; i++)
        {   
            if(line[i] == "")
            {
                line[i] = $i
            }
            else
            {
                line[i] = line[i]" "$i
            }
        }
    }
    END{
         for(i=1; i<=NF; i++)
         {
             print line[i]
         }
       }
    ' file.txt