Bash从列名中检索列号 [英] Bash retrieve column number from column name

查看:89
本文介绍了Bash从列名中检索列号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有更好的方法(例如AWK中的一个班轮),我可以从具有列名的标题中获取表中的列号?我希望能够独立于实际的列号来处理一列(例如,添加另一列时,无需更改脚本).

Is there a better way (such as a one liner in AWK) where I can get the column number in a table with headings from a column name? I want to be able to process a column independent of what the column number actually is (such as when another column is added the script will not need to change).

例如,在"table.tsv"中给出下表:

For example, given the following table in "table.tsv":

ID  Value   Target  Not Used
1   5   9   11
2   4   8   12
3   6   7   10

我可以使用以下方法在目标"列上进行排序:

I can do a sort on the "Target" column using:

#!/bin/bash
(IFS=$'\t'; read -r; printf "%s\n" "$REPLY"; i=0; for col in $REPLY; do
    ((++i))
    [ "$col" == "Target" ] && break
done; sort -t$'\t' "-k$i,${i}n") < table.tsv

有没有一种方法可以在没有for循环的情况下(或者至少要清理一点)?

Is there a way to do it without the for loop (or at least clean it up a little)?

给定脚本的预期输出为:

The expected output of the given script is:

ID      Value   Target  Not Used
3       6       7       10
2       4       8       12
1       5       9       11

但是,我试图举一个我想做的事的例子.我想通过几个程序传递/过滤我的表,因此标题和所有列都应保留:在每个步骤都进行处理. 用伪代码,我想做的是:

However, I was trying to give an example of what I was trying to do. I want to pass/filter my table through several programs so the headings and all columns should be preserved: just have processing occur at each step. In pseudo code, what I would like to do is:

print headings from stdin
i=$(magic to determine column position given "Target")
sort -t$'\t' "-k$i,${i}n"  # or whatever processing is required on that column

推荐答案

具有大量管道的另一种替代方法

another alternative with a lot of pipes

$ head -1 table | tr -s ' ' '\n' | nl -nln |  grep "Target" | cut -f1

提取第一行,转置,编号行,查找列名,提取编号

extract first row, transpose, number lines, find column name, extract number

或者,awk进行救援!

$ awk -v RS='\t' '/Target/{print NR; exit}' file.tsv
3

这篇关于Bash从列名中检索列号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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