gpt4 book ai didi

awk - 如何每列打印使用awk

转载 作者:行者123 更新时间:2023-12-01 23:21:59 24 4
gpt4 key购买 nike

a.txt的内容

name age
alice 21
ryan 30

#test.sh
nf=`awk '{print NF; exit}' a.txt`
for((i=1;i<=$nf;i++))
{
awk '{print $i}' ./a.txt
}

我期望的结果是按列打印,但实际结果是将所有内容打印两次。

我的预期输出是

name
alice
ryan
age
21
30

实际输出为

name age
alice 21
ryan 30
name age
alice 21
ryan 30

最佳答案

这可以在单个 awk 本身中完成,请尝试以下操作;使用您的节目样本编写和测试。

awk -v tot="0" '
{
for(i=1;i<=NF;i++){
arr[i]=(arr[i]?arr[i] ORS:"")$i
}
tot=(tot>NF?tot:NF)
}
END{
for(i=1;i<=tot;i++){
print arr[i]
}
}
' Input_file

说明: 为以上添加详细说明。

awk -v tot="0" '          ##Starting awk program from here, setting tot to 0 here.
{
for(i=1;i<=NF;i++){ ##Traversing through all fields here.
arr[i]=(arr[i]?arr[i] ORS:"")$i ##Creating arr with index of i and keep appending current field value in it.
}
tot=(tot>NF?tot:NF) ##Creating tot by seeing current total number of fields, to get highest NF value here.
}
END{ ##Starting END block of this program from here.
for(i=1;i<=tot;i++){ ##Running for loop from i=1 to till tot value here.
print arr[i] ##Printing array with index of i here.
}
}
' Input_file ##Mentioning Input_file name here.

关于awk - 如何每列打印使用awk,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67964796/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com