从另一个文件添加列

时间:2016-12-17 16:41:51

标签: linux bash shell csv

我是BASH脚本中的新手。我有一个csv文件,其中2列用逗号分隔。

ASDP01,01989015064
KSDP03,01988683270
KSDP06,01945993069
CSDP11,01990721863
CSDP13,01955883155
ASDP12,01953889744
CSDP11,01956798684
ASDP11,01959969994
KSDP01,01924824056

我想从另一个文本文件中添加另外两列。 这是写在文本文件中的:

662,2016-12-31

从tex文件添加后,csv文件将如下所示

ASDP01,01989015064,662,2016-12-31
KSDP03,01988683270,662,2016-12-31
KSDP06,01945993069,662,2016-12-31
CSDP11,01990721863,662,2016-12-31
CSDP13,01955883155,662,2016-12-31
ASDP12,01953889744,662,2016-12-31
CSDP11,01956798684,662,2016-12-31
ASDP11,01959969994,662,2016-12-31
KSDP01,01924824056,662,2016-12-31

任何人都可以帮我这个吗?

3 个答案:

答案 0 :(得分:1)

我认为file2.csv只包含一行662,2016-12-31

string="$(cat file2.csv)"
sed 's/.*/&,'"$string"'/' file1.csv > new.csv

输出到new.csv:

ASDP01,01989015064,662,2016-12-31
KSDP03,01988683270,662,2016-12-31
KSDP06,01945993069,662,2016-12-31
CSDP11,01990721863,662,2016-12-31
CSDP13,01955883155,662,2016-12-31
ASDP12,01953889744,662,2016-12-31
CSDP11,01956798684,662,2016-12-31
ASDP11,01959969994,662,2016-12-31
KSDP01,01924824056,662,2016-12-31

请参阅:The Stack Overflow Regular Expressions FAQ

答案 1 :(得分:0)

您也可以使用awk来完成结果。

#cat file1
KSDP01,01989015064
KSDP03,01988683270
KSDP06,01945993069
CSDP11,01990721863
CSDP13,01955883155
ASDP12,01953889744
CSDP11,01956798684
ASDP11,01959969994
KSDP01,01924824056

#cat file2
662,2016-12-31

#awk -v f2content="$(<file2)" '{$0=($0 "," f2content)}1' file1
KSDP01,01989015064,662,2016-12-31
KSDP03,01988683270,662,2016-12-31
KSDP06,01945993069,662,2016-12-31
CSDP11,01990721863,662,2016-12-31
CSDP13,01955883155,662,2016-12-31
ASDP12,01953889744,662,2016-12-31
CSDP11,01956798684,662,2016-12-31
ASDP11,01959969994,662,2016-12-31
KSDP01,01924824056,662,2016-12-31

请参阅[ awk concatenation ]

答案 2 :(得分:0)

另一个sed替代

$ sed 's/$/,'"$(cat file2)"'/' file1