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

簡單的意思是有一個文件內容中每一行中用空格隔開,且行數與列數相等,請輸出時,第一列的作為第一行,第二列的作為第二行,說白了就是行列轉換

將所有內容存儲到一個二維數組中,之后按列輸出每一行,即可。

答案:

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]。

答案二:

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]; } }'  file.txt

使用一維數組,記錄每一列的組合串即可,當是第一行時賦值,否則都是累加,即字符串拼接。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM