194 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.

Example:

If file.txt has the following content:

name age
alice 21
ryan 30

Output the following:

name alice ryan
age 21 30

Link: https://leetcode.com/problems/transpose-file/description/

思路

行列转换,用awk方法来解决

将同一列用空格拼接起来,然后输出

代码

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

知识点温故

1、awk相关

BEGIN 模式:是指 awk 将在读取任何输入行之前立即执行 BEGIN 中指定的动作。

END 模式:是指 awk 将在它正式退出前执行 END 中指定的动作。

2、字符串拼接

只需要将变量与双引号连接在一起即可。

results matching ""

    No results matching ""