gpt4 book ai didi

awk - 根据字段数添加其他字段

转载 作者:行者123 更新时间:2023-12-04 11:37:23 24 4
gpt4 key购买 nike

我在文件中有以下格式的数据

"123","XYZ","M","N","P,Q"
"345",
"987","MNO","A,B,C"
我总是希望在行中有 5 个条目,因此如果字段数为 2,则需要添加 3 个额外的 ("")。
"123","XYZ","M","N","P,Q" 
"345","","","",""
"987","MNO","A,B,C","",""
我查看了页面上的解决方案
Add Extra Strings Based on count of fields- Sed/Awk
它有非常相似的要求,但是当我尝试时它失败了,因为我在字段中也有逗号 (,)。
谢谢。

最佳答案

在 GNU 中 awk使用您显示的示例,请尝试以下代码。

awk -v s1="\"" -v FPAT='[^,]*|"[^"]+"' '
BEGIN{ OFS="," }
FNR==NR{
nof=(NF>nof?NF:nof)
next
}
NF<nof{
val=""
i=($0~/,$/?NF:NF+1)
for(;i<=nof;i++){
val=(val?val OFS:"")s1 s1
}
sub(/,$/,"")
$0=$0 OFS val
}
1
' Input_file Input_file
说明:为上述添加详细说明。
awk -v s1="\"" -v FPAT='[^,]*|"[^"]+"' ' ##Starting awk program from here setting FPAT to csv file parsing here.
BEGIN{ OFS="," } ##Starting BEGIN section of this program setting OFS to comma here.
FNR==NR{ ##Checking condition FNR==NR here, which will be true for first time file reading.
nof=(NF>nof?NF:nof) ##Create nof to get highest NF value here.
next ##next will skip all further statements from here.
}
NF<nof{ ##checking if NF is lesser than nof then do following.
val="" ##Nullify val here.
i=($0~/,$/?NF:NF+1) ##Setting value of i as per condition here.
for(;i<=nof;i++){ ##Running loop till value of nof matches i here.
val=(val?val OFS:"")s1 s1 ##Creating val which has value of "" in it.
}
sub(/,$/,"") ##Removing ending , here.
$0=$0 OFS val ##Concatinate val here.
}
1 ##Printing current line here.
' Input_file Input_file ##Mentioning Input_file names here.

编辑:在此处添加此代码,其中保留一个名为 nof 的变量在这里我们可以给出我们应该在所有缺失行中添加最小的字段数值,如果任何行的字段值超过最小字段值,那么它将使用该值在缺失的字段行中添加许多字段。
awk -v s1="\"" -v nof="5" -v FPAT='[^,]*|"[^"]+"' '
BEGIN{ OFS="," }
FNR==NR{
nof=(NF>nof?NF:nof)
next
}
NF<nof{
val=""
i=($0~/,$/?NF:NF+1)
for(;i<=nof;i++){
val=(val?val OFS:"")s1 s1
}
sub(/,$/,"")
$0=$0 OFS val
}
1
' Input_file Input_file

关于awk - 根据字段数添加其他字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68017415/

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