按列名打印列内容 [英] Print column contents by column name

查看:71
本文介绍了按列名打印列内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想向awk或cut命令输入字符串名称(即"COL2"),并打印与该列标题字符串匹配的列.

I want to input a string name (i.e. "COL2") to an awk or cut command and print the column that matches that column header string.

数据文件如下:

COL1 COL2 COL3 COL4 COL5 COL6
a a b d c f
a d g h e f
c v a s g a

如果我输入了COL3,我希望它打印第三列,依此类推.我认为awk可能是最容易使用的东西,但是cut可能也可以.我只是不确定如何去做.

If I pass in COL3, I want it to print the third column, etc. I'm thinking awk might be the easiest thing to use, but cut may also work. I'm just not sure how to go about doing this.

推荐答案

针对上述问题(如果您有兴趣)Akk 1衬板:

Awk 1 liner for above problem (if you are interested):

awk -v col=COL2 'NR==1{for(i=1;i<=NF;i++){if($i==col){c=i;break}} print $c} NR>1{print $c}' file.txt

awk -v col=COL3 'NR==1{for(i=1;i<=NF;i++){if($i==col){c=i;break}} print $c} NR>1{print $c}' file.txt

只需使用 -vcol = 标志传递您的列名COL1,COL2,COL3等.

Just pass your column name COL1, COL2, COL3 etc with -vcol= flag.

这篇关于按列名打印列内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆