Shell练习 行列转换

原题: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

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

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

答案一:

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

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

答案二:
使用一维数组,记录每一列的组合串即可,当是第一行时赋值,否则都是累加,即字符串拼接。

awk '{ for(i=1;i<=NF;i++){ if(NR==1){ arr[i]=$i }else{ arr[i]=arr[i]" "$i } } } END{ for(i=1;i<=NF;i++){print arr[i]} }' nowcoder.txt

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

原文地址:https://www.cnblogs.com/chenjo/p/14541321.html