如果关键字段匹配,则Bash连接字段

如果关键字段匹配,则Bash连接字段,bash,csv,string-concatenation,Bash,Csv,String Concatenation,我得到了这样的文本文件:id;名字;客户发票;注释(这是一个示例) 我要做的是根据客户机的不同,将发票字段连接到每行末尾的另一个字段中。我只能使用bash或unix cli工具(awk、sed、cut等) 在这种情况下,应产生: 001;peter;35621;C132;foo;;C132/Y456 002;jane;12345;A546;;A546 003;robert;78945;Z456;some comments;Z456/L546 001;peter;35621;Y456;blabla

我得到了这样的文本文件:id;名字;客户发票;注释(这是一个示例)

我要做的是根据客户机的不同,将发票字段连接到每行末尾的另一个字段中。我只能使用bash或unix cli工具(awk、sed、cut等) 在这种情况下,应产生:

001;peter;35621;C132;foo;;C132/Y456
002;jane;12345;A546;;A546
003;robert;78945;Z456;some comments;Z456/L546
001;peter;35621;Y456;blabla;C132/Y456
004;terry;89740;T897;;T897
003;robert;78945;L546;bar;Z456/L546
到目前为止我所做的:(但我对结果并不满意,因为它看起来真的很难看)

#/bin/bash
file=“myfile.txt”
而IFS=\;读取id firstname客户端发票注释
做
catInvoice=“”
而IFS=\;阅读xid xfirstname xclient xinvoice xcomments
做
如果[$client==$xclient]
然后
catInvoice=“$catInvoice/$xinvoice”
fi
完成<$file
catInvoice=`echo$catInvoice|sed's/^\/'`
echo“$id;$firstname;$client;$invoice;$comments;$catInvoice”
完成<$file
有什么建议吗?
谢谢。

两次传递到文件,但完成了以下操作:

awk '
BEGIN{FS=OFS=";"}
NR==FNR{a[$2]=(a[$2])?a[$2]"/"$4:$4;next}
{print $0,a[$2]}' textfile textfile
输出:假设您的示例文件中有输入错误(例如,Robert缺少输出中显示的L546发票)。
罗伯特是怎么得到L546发票的?你的样品文件中没有。是的,对不起,我的错。现在更正。谢谢,太棒了…正是我要找的。我会小心地把这个放在枕头下;)。。。谢谢你。
#!/bin/bash

file="myfile.txt"

while IFS=\; read id firstname client invoice comments
do
    catInvoice=""
    while IFS=\; read xid xfirstname xclient xinvoice xcomments
    do
        if [ $client == $xclient ]
            then
                catInvoice="$catInvoice/$xinvoice"
        fi
    done < $file
    catInvoice=`echo $catInvoice | sed 's/^\///'`
    echo "$id;$firstname;$client;$invoice;$comments;$catInvoice"
done < $file
awk '
BEGIN{FS=OFS=";"}
NR==FNR{a[$2]=(a[$2])?a[$2]"/"$4:$4;next}
{print $0,a[$2]}' textfile textfile
$ cat textfile 
001;peter;35621;C132;foo
002;jane;12345;A546;
003;robert;78945;Z456;some comments
001;peter;35621;Y456;blabla
004;terry;89740;T897;
003;robert;78945;L546;bar

$ awk 'BEGIN{FS=OFS=";"}NR==FNR{a[$2]=(a[$2])?a[$2]"/"$4:$4;next}{print $0,a[$2]}' textfile textfile
001;peter;35621;C132;foo;C132/Y456
002;jane;12345;A546;;A546
003;robert;78945;Z456;some comments;Z456/L546
001;peter;35621;Y456;blabla;C132/Y456
004;terry;89740;T897;;T897
003;robert;78945;L546;bar;Z456/L546