您的位置:首页 > 运维架构 > Shell

leetcode-shell-194. Transpose File

2016-06-16 16:04 483 查看
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完成的,然后自己写了一遍,感觉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表示行数
首先遍历整个文件,将字段记录到数组中,然后行列互换输出。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: