檔案 a 包含欄位名稱:
timestamp,name,ip
檔案 b 包含值:
2021-12-17 16:01:19.970,app1,10.0.0.0
2021-12-17 16:01:19.260,app1,10.0.0.1
當我按如下方式使用 awk 時:
awk 'BEGIN{FS=",";OFS="\n"} {if(NR%3==0){print "----"};$1=$1;print;}' b
我得到:
----
2021-12-17 16:01:19.970
app1
10.0.0.0
----
2021-12-17 16:01:19.260
app1
10.0.0.1
有什么方法可以合并每一行中的鍵:值?我想要的輸出是:
----
timestamp:2021-12-17 16:01:19.970
app:app1
ip:10.0.0.0
----
timestamp:2021-12-17 16:01:19.260
app:app1
ip:10.0.0.1
uj5u.com熱心網友回復:
使用您顯示的示例,請嘗試以下awk程式。
awk '
BEGIN{ FS="," }
FNR==NR{
for(i=1;i<=NF;i ){
heading[i]=$i
}
next
}
{
print "----"
for(i=1;i<=NF;i ){
print heading[i]":"$i
}
}
' filea fileb
說明:為以上添加詳細說明。
awk ' ##Starting awk program from here.
BEGIN{ FS="," } ##Stating BEGIN section of this program and set FS to , here.
FNR==NR{ ##Checking condition which will be TRUE when filea is being read.
for(i=1;i<=NF;i ){ ##Traversing through all fields here.
heading[i]=$i ##Setting heading array index as i and value as current field.
}
next ##next will skip all further statements from here.
}
{
print "----" ##printing ---- here.
for(i=1;i<=NF;i ){ ##Traversing through all fields here.
print heading[i]":"$i ##Printing heading with index i and colon and value of current field.
}
}
' filea fileb ##Mentioning Input_file names here.
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/383719.html
