shell 更新文本文件的一列并将变量名写入输出

dfty9e19  于 2023-04-07  发布在  Shell
关注(0)|答案(1)|浏览(83)

我有一个带有ID和价格的物品记录,并尝试根据另一个“参考文件”更新其中一些物品的价格,其格式为Item# NewPrice OutFile。最终,我们将有与ref文件中的#行一样多的输出记录(这里有4个输出)。OutFiles除了调整后的项目外,将与原始文件相似。下面是我的文件和awk脚本,它不工作。谢谢你的帮助。

Main file  [Item # current_value]:
Item  1  20 
Item  2  30
Item  3  40

Reference file  [Item# new_value outputfile]
1  22  It1_22
1  25  It1_25
2  32  It2_32
3  45  It3_45

Expected Output files:
(It1_22)
Item,1,22
Item,2,30
Item,3,40

(It1_25)
Item,1,25
Item,2,30
Item,3,40

(It2_32)
Item,1,20
Item,2,32
Item,3,40

(It3_45)
Item,1,20
Item,2,30
Item,3,45

我的脚本不生成任何文件:

awk 'BEGIN{OFS=","};FNR == NR{a[$1]=$2;d=$3;next} $2 in a{print $1,$2,a[$2];next}1' ref  main > d
nnt7mjpx

nnt7mjpx1#

这里有一个解决方案,没有任何错误处理丢失的值等。要保持数据文件的顺序,将每个与行号关联,并在打印时恢复。

$ awk -v OFS=, 'NR==FNR{k=$2; n[k]=$1; v[k]=$3; ord[NR]=k; next}                        
                       {for(i=1;i<=length(ord);i++) 
                          {k=ord[i]; 
                           print n[k],k,k==$1?$2:v[k] > $3}}' mainfile reffile 
                                        
$ head It*
==> It1_22 <==
Item,1,22
Item,2,30
Item,3,40

==> It1_25 <==
Item,1,25
Item,2,30                                                                                                      
Item,3,40                                                                                                      
                                                                                                               
==> It2_32 <==                                                                                                 
Item,1,20                                                                                                      
Item,2,32                                                                                                      
Item,3,40                                                                                                      
                                                                                                               
==> It3_45 <==                                                                                                 
Item,1,20                                                                                                      
Item,2,30                                                                                                      
Item,3,45

相关问题