首页 > 其他 > 详细

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

时间:2019-02-22 01:06:03      阅读:220      评论:0      收藏:0      [点我收藏+]

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

技术分享图片

 

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

原文:https://www.cnblogs.com/douzujun/p/10416098.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!