码迷,mamicode.com
首页 > 系统相关 > 详细

Shell练习 行列转换

时间:2016-04-03 00:12:16      阅读:461      评论:0      收藏:0      [点我收藏+]

标签:

原题:https://leetcode.com/problems/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

简单的意思是有一个文件内容中每一行中用空格隔开,且行数与列数相等,请输出时,第一列的作为第一行,第二列的作为第二行,说白了就是行列转换。

将所有内容存储到一个二维数组中,之后按列输出每一行,即可。

答案:

cat file.txt|awk ‘BEGIN{c=0;} {for(i=1;i<=NF;i++) {num[c,i] = $i;} c++;} END{ for(i=1;i<=NF;i++){str=""; for(j=0;j<NR;j++){ if(j>0){str = str" "} str= str""num[j,i]}printf("%s\n", str)} }‘

其中使用到awk命令,而在awk中有BEGIN(开始),END(结束),NF(列数,从1开始),NR(行数,从1开始)。

字符串的拼接,如str=str""num[j,i]。

 

Shell练习 行列转换

标签:

原文地址:http://www.cnblogs.com/xiaoxian1369/p/5348592.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!