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


    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

    知识点: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

  • 相关阅读:
    今天我正式走出公司...
    PHP图片处理函数
    PHP缓存知识-转载
    Nginx 服务器伪静态配置实例
    PHP防止跨站攻击的脚本
    <
    <
    <- OPENGL 10 NormalMAP ->
    <-OPENGL 9-> 阴影篇
    - OPENGL8
  • 原文地址:https://www.cnblogs.com/douzujun/p/10416098.html
Copyright © 2020-2023  润新知