簡體   English   中英

使用awk按列名獲取特定列號

[英]Get a specific column number by column name using awk

我有n個文件,在這些文件中,每個文件中的不同列號都會給出一個名為“thrudate”的特定列。

我只想一次性從所有文件中提取此列的值。 所以我嘗試使用awk。 在這里,我只考慮一個文件,並提取thrudate的值

awk -F, -v header=1,head="" '{for(j=1;j<=2;j++){if($header==1){for(i=1;i<=$NF;i++){if($i=="thrudate"){$head=$i;$header=0;break}}} elif($header==0){print $0}}}' file | head -10

我是如何接近的:

  • 使用find命令查找所有類似文件,然后對每個文件執行第二步
  • 循環第一行中的所有字段,檢查列名稱,標題值為1(初始化為1以僅檢查第一行),一旦與'thrudate'匹配,我將標題設置為0,然后從此循環中斷。
  • 一旦我得到列號,然后打印每行。

您可以使用以下awk腳本:

print_col.awk

# Find the column number in the first line of a file 
FNR==1{
    for(n=1;n<=NF;n++) {
        if($n == header) {
            next
        }
    }
}

# Print that column on all other lines
{
    print $n
}

然后使用find在每個文件上執行此腳本:

find ... -exec awk -v header="foo" -f print_col.awk {} +

在評論中,您已經要求提供可以根據其標題名稱打印多個列的版本。 您可以使用以下腳本:

print_cols.awk

BEGIN {
    # Parse headers into an assoc array h
    split(header, a, ",")
    for(i in a) {
        h[a[i]]=1
    }   
}

# Find the column numbers in the first line of a file
FNR==1{
    split("", cols) # This will re-init cols
    for(i=1;i<=NF;i++) {
        if($i in h) {
            cols[i]=1
        }
    }   
    next
}

# Print those columns on all other lines
{
    res = ""
    for(i=1;i<=NF;i++) {
        if(i in cols) {
            s = res ? OFS : ""
            res = res "" s "" $i
        }
    }   
    if (res) {
        print res 
    }   
}

像這樣稱呼它:

find ... -exec awk -v header="foo,bar,test" -f print_cols.awk {} +

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM