leetcode-shell-194. Transpose File

来源:互联网 发布:vb视频大学生自学网 编辑:程序博客网 时间:2024/05/28 11:30

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 agealice 21ryan 30


Output the following:

name alice ryan
age 21 30



题意:行列互换
思路:没有思路,看了别人使用awk完成的,然后自己写了一遍,感觉awk好强大
最终shell脚本:
#! /bin/sh
awk '
{
    for(i=1;i<=NF;i++)
    {
        a[NR,i]=$i
    }
}

END {
    for(j=1;j<=NF;j++)
    {
        str=a[1,j]
        for(i=2;i<=NR;i++)
        {
            str=str" "a[i,j]
        }
        print str
    }
}
' file.txt

NF表示列数
NR表示行数
首先遍历整个文件,将字段记录到数组中,然后行列互换输出。
0 0