首页 > 系统服务 > 详细

Shell练习 行列转换

时间:2016-04-03 00:11:51      阅读:208      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!