如何在Unix中的每一行末尾添加一个值/数据

时间:2013-06-25 17:56:28

标签: unix

我有fileAfileB数据,如下所示

fileA

,,"user1","email"
,,"user2","email"
,,"user3","email"
,,"user4","email"

fileB

,,user2,location
,,user4,location
,,user1,location
,,user3,location

我想在fileA上搜索fileB用户,只获取位置并将其添加到fileA /或其他文件

输出期望像

,,"user1","email",location
,,"user2","email",location
,,"user3","email",location
,,"user4","email",location

我正在尝试使用逻辑,同时获取fileA用户名并在fileB上搜索以获取该位置。但未能将fileA添加回来

非常感谢您的帮助

2 个答案:

答案 0 :(得分:1)

这应该有效:

for user in `awk -F\" '{print $2}' fileA`
do
   loc=`grep ${user} fileB | awk -F',' '{print $4}'`
   sed -i "/${user}/ s/$/,${loc}/" fileA
done

添加示例:

$ cat fileA
,,"user1","email"
,,"user2","email"
,,"user3","email"
,,"user4","email"

$ cat fileB
,,user2,location2
,,user4,location4
,,user1,location1
,,user3,location3

$ for user in `awk -F\" '{print $2}' fileA`; do echo ${user}; loc=`grep ${user} fileB |    awk -F',' '{print $4}'`; echo ${loc}; sed -i "/${user}/ s/$/,${loc}/" fileA; done

$ cat fileA
,,"user1","email",location1
,,"user2","email",location2
,,"user3","email",location3
,,"user4","email",location4

说明不明确,但根据问题,您可以使用以下命令将值/数据附加到Unix中每行的末尾

sed -i '/search_pattern/ s/$/string_to_be_appended/' filename

答案 1 :(得分:1)

您可以在awk

中完全执行此操作
awk -F, '
NR==FNR{a[$3]=$4;next}
{for(x in a) if(index($3,x)>0) print $0","a[x]}' file2 file1

测试:

$ cat file1
,,"user1","email"
,,"user2","email"
,,"user3","email"
,,"user4","email"

$ cat file2
,,user2,location2
,,user4,location4
,,user1,location1
,,user3,location3

$ awk -F, 'NR==FNR{a[$3]=$4;next}{for(x in a) if(index($3,x)>0) print $0","a[x]}' file2 file1
,,"user1","email",location1
,,"user2","email",location2
,,"user3","email",location3
,,"user4","email",location4