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.

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 ' ' file: ' ' 中是处理语句

BEGIN {
    # 执行之前的操作,一般是赋值
}
{
    # 中间是对每一行的操作 
}
END {
    # 处理完后的操作,一般是格式化输出
}

解法:用一个数组s,里面有NF个元素,其中NF(列号)是当前记录的总字数。对于第一个记录,直接存到相应的s[i]中,最后s[i[对应源文件一列的内容。

#!/bin/bash

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

LeetCode(194.Transpose File)(awk进阶)

 

相关文章:

  • 2022-12-23
  • 2021-11-18
  • 2021-09-06
  • 2022-01-08
  • 2021-08-23
  • 2022-01-15
  • 2021-11-15
猜你喜欢
  • 2021-05-23
  • 2022-01-03
  • 2021-11-17
  • 2021-11-13
  • 2022-01-14
  • 2021-12-24
  • 2021-09-12
相关资源
相似解决方案