如何连接来自不同文件的单词

问题描述

我是在 bash 中学习 shell 脚本的初学者。

我有两个不同的文件

专业人士.txt

ProID:ProName:cslocal:n1:n2

12345:John Joe:CSBerlin:0:0
98765:Miller Key:CSMoscow:0:1

人物.txt

peopleID:personName:Age:local:phone:n3

10001:Greg Linn:86:Berlin:912345678:0
10002:Peter Ronner:65:London:962345678:0
10003:Kelly Sena:91:Moscow:966645678:0
10004:Anne Tyler:87:Moscow:984973897:0

我需要做一个脚本,所以我得到一个输出文件,如:

输出.txt

ProName:ProID:personName:personID:cslocal

personName将对应于Professional所在城市的人

Miller Key:98765:Kelly Sena:10003:CSMoscow
Miller Key:98765:Anne Tyler:10004:CSMoscow

问候。

解决方法

export LANG=en_US.UTF-8
export PATH=/usr/local/bin:$PATH
export GEM_HOME="$HOME/.gem"
echo "PATH: $PATH"
 cd Projectname/directory // change only this line
pod install --verbose
  • join 正是您所需要的:它根据给定的列匹配两个列表。但它需要按列对列表进行排序,这就是其余代码的作用。
  • join -t: -1 3 -2 4 -o1.2,1.1,2.2,2.1,2.4 \ <(sort -t: -k3,3 Professionals.txt ) \ <(sort -t: -k4,4 People.txt | sed 's/^\(\([^:]*:\)\{3\}\)/\1CS/') sortjoin 指定列分隔符
  • -t-1 告诉 join 在各自的列表中加入哪些列
  • -2 告诉 sort 对哪一列进行排序,-k 表示“仅使用第 3 列”
  • 3,3 告诉 join 输出哪些列
  • sed 用于为 People.txt 列表中的城市添加 -o 前缀,以便两个列表中的名称匹配
,

使用 GNU awk:

awk -F: 'FNR==NR { map[$4][$2]=$2":"$1;next } { for ( i in map[substr($3,3)] ) { print $2":"$1":"map[substr($3,3)][i]":"$3 } }' People.txt Professionals.txt

说明:

awk -F: 'FNR==NR {                                                   # Process the first file (People.txt)
                  map[$4][$2]=$2":"$1;                               # Build a two dimensional array with the city as the first index and the name as the second. Have the name and the Id as the value
                  next 
                } 
                {                                                    # Process the second file
                  for ( i in map[substr($3,3)] ) { 
                    print $2":"$1":"map[substr($3,3)][i]":"$3        # Loop through the array where the first index is equal to the 3rd ":" separated field from the 3rd character onwards of the existing line,printing the data along with additional data from the existing line.
                  } 
                 }' People.txt Professionals.txt