0

我有以下文件,

总计.txt

order1,5,item1
order2,6,item2
order3,7,item3
order4,6,item4
order8,9,item8

改变了.txt

order3,8,item3
order8,12,item8

total.txt 是总订单数据,changed.txt 是最近更改的数据。我想将最近的更改与总数合并,我希望输出为,

输出.txt

order1,5,item1
order2,6,item2
order3,8,item3
order4,6,item4
order8,12,item8

注意:total.txt(第 3 和第 5)行的第 2 列用 changed.txt 文件更新

我已经使用下面nawk的来比较第一个 coulmn,但无法将其打印到输出文件。请帮助完成以下命令

nawk -F"," 'NR==FNR {a[$1]=$2;next} ($1 in a) "print??"' total.txt changed.txt

4

4 回答 4

3

其他awk

awk -F, 'FNR==NR {a[$1]=$0;next} {print (a[$1]?a[$1]:$0)}' changed.txt total.txt
order1,5,item1
order2,6,item2
order3,8,item3
order4,6,item4
order8,12,item8

它是如何工作的?

awk -F, '                       # set field separator to ","
    FNR==NR {                   # run this only on first file "changed.txt"
        a[$1]=$0                # store "changed.txt" in array "a" using first field as index
        next                    # skip to next record
    }
        {                       # run this when second file is read "total.txt"
        print (a[$1]?a[$1]:$0)  # if filed exist in "changed" use that, else use "total"
    }' changed.txt total.txt    # read these files
于 2013-11-09T21:24:39.333 回答
2

这可能对您有用(GNU sed):

sed -r 's/^([^,]*,).*/s|^\1.*|&|/' changed.txt | sed -f - total.txt > output.txt
于 2013-11-09T22:02:40.530 回答
1

这个单线对你有用吗?

awk -F, 'NR==FNR{a[$1]=$0;next}a[$1]{$0=a[$1]}7' change total

测试:

kent$  head c t
==> c <==
order3,8,item3
order8,12,item8

==> t <==
order1,5,item1
order2,6,item2
order3,7,item3
order4,6,item4
order8,9,item8

kent$  awk -F, 'NR==FNR{a[$1]=$0;next}a[$1]{$0=a[$1]}7' c t
order1,5,item1
order2,6,item2
order3,8,item3
order4,6,item4
order8,12,item8
于 2013-11-09T21:50:38.570 回答
0

读取第一个changed.txt文件并将数据保存在哈希中。然后比较其中是否total.txt存在第一个字段并替换该值:

awk '
    BEGIN { FS = OFS = "," } 
    NR == FNR { a[$1] = $2; next } 
    { if ( $1 in a ) { $2 = a[$1] } print }
' changed.txt total.txt

它产生:

order1,5,item1
order2,6,item2
order3,8,item3
order4,6,item4
order8,12,item8
于 2013-11-09T21:23:39.057 回答