我正在嘗試使用以下 awk 腳本獲取兩個檔案之間的差異:
awk 'NR==FNR{
a[$0]
next
}
{
if($0 in a)
delete a[$0]
else
a[$0]
}
END {
for(i in a) {
$0=i
sub(/[^.]*$/,substr(tolower($1),1,length($1)-1),$3)
print
}
}' [ab].yaml
a.yaml檔案:
NAME_VAR: {{ .Data.data.name_var }}
SOME_VALUE: {{ .Data.data.some_value }}
ONE_MORE: {{ .Data.data.one_more }}
和b.yaml檔案:
NAME_VAR: {{ .Data.data.name_var }}
SOME_VALUE: {{ .Data.data. }}
ONE_MORE: {{ .Data.data. }}
ADD_THIS: {{ .Data.data. }}
該腳本應合并差異并替換大括號中包含的內容。
是這樣的:
ADD_THIS: {{ .Data.data.add_this }}
SOME_VALUE: {{ .Data.data.some_value }}
ONE_MORE: {{ .Data.data.one_more }}
但它重復了我的輸出:
ADD_THIS: {{ .Data.data.add_this }}
SOME_VALUE: {{ .Data.data.some_value }}
ONE_MORE: {{ .Data.data.one_more }}
SOME_VALUE: {{ .Data.data.some_value }}
ONE_MORE: {{ .Data.data.one_more }}
如果有新變數,腳本應該替換大括號中包含的所有內容。
uj5u.com熱心網友回復:
假設:
- 資料組件將始終是
.Data.data.<some_string>或.Data.data.
采取稍微不同的方法:
awk '
NR==FNR { a[$1]=$3
next
}
$1 in a { if ($3 == a[$1]) { # if $1 is an index of a[] and $3 is an exact match then ...
delete a[$1] # delete the a[] entry (ie, these 2 rows are identical so discard both)
}
else
if (length($3) > length(a[$1])) # if $1 is an index of a[] but $3 does not match, and $3 is longer then ...
a[$1]=$3 # update a[] with the new/longer entry
next # skip to next input line
}
{ a[$1]=$3 } # if we get here then $1 has not been seen before so add to a[]
END { for (i in a) { # loop throug indices
val=a[i] # make copy of value
sub(/[^.]*$/,tolower(i),val) # strip off everything coming after the last period and add the lowercase of our index
sub(/:$/,"",val) # strip the ":" off the end of the index
print i,"{{",val,"}}" # print our new output
}
}
' [ab].yaml
這會產生:
SOME_VALUE: {{ .Data.data.some_value }}
ADD_THIS: {{ .Data.data.add_this }}
ONE_MORE: {{ .Data.data.one_more }}
注意:如果輸出需要重新排序,那么將結果通過管道傳輸到適當的sort命令會更容易
至于為什么 OP 的當前代碼會列印重復的行......
END{...}像這樣修改塊:
END { for (i in a)
print i,a[i]
}
這應該顯示代碼保存了來自兩個檔案的輸入,但由于沒有努力匹配“重復項”(通過匹配$1),結果是兩組輸入(現在修改為看起來相同)被列印到標準輸出。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/536827.html
標籤:狂欢awkyaml
上一篇:Jenkins腳本中的sed命令
