[英]How to replace a number to another number in a specific column using 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
我是如何接近的:
您可以使用以下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.