• 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
    ", 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

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

  • 相关阅读:
    [CF1076D] Edge Deletion
    [CF1081D] Maximum Distance
    [CF1095F] Make It Connected
    [CF1328E] Tree Queries
    [CF1328F] Make k Equal
    Codeforces Round #629 (Div. 3) 总结
    [CF1131D] Gourmet choice
    [CF1176D] Recover it!
    [CF1205B] Shortest Cycle
    [CF1213G] Path Queries
  • 原文地址:https://www.cnblogs.com/xiaoxian1369/p/5348592.html
Copyright © 2020-2023  润新知