简体   繁体   English

bash-根据file2中的ID查找file1中的名称

[英]bash - Find names in file1 according to IDs in file2

Sorry if this is duplicate, but I searched and haven't found exactly same question. 抱歉,如果这是重复的,但是我搜索了却没有发现完全相同的问题。 So I have 所以我有

File1: 文件1:
Aaron ID00456 亚伦ID00456
Brad ID00123 布拉德ID00123
Cassie ID00789 卡西ID00789
Doug ID12345 道格ID12345
Ethan ID05555 伊桑ID05555

File2: 文件2:
ID12345 ID12345
ID00123 编号
ID00456 ID00456

Keeping the order of IDs in File2, I'd like to have output File3 as: 保持ID在File2中的顺序,我希望将File3输出为:
Doug ID12345 道格ID12345
Brad ID00123 布拉德ID00123
Aaron ID00456 亚伦ID00456

Try this script (suppose File1.txt and File2.txt are in the same directory of the script). 尝试使用此脚本(假设File1.txt和File2.txt位于脚本的同一目录中)。

#!/bin/bash
while read -r ID2
do
  while read -r NAME ID1
  do
    if [ "$ID1" = "$ID2" ]
    then
      echo $NAME $ID1 >> File3.txt
    fi
  done < File1.txt
done < File2.txt

Then find File3.txt in the same directory with the content: 然后在与内容相同的目录中找到File3.txt:

Doug ID12345
Brad ID00123
Aaron ID00456

awk to the rescue! awk解救!

$ awk 'NR==FNR {a[$2]=$1; next} 
               {print a[$1],$1}' file1 file2

Doug ID12345
Brad ID00123
Aaron ID00456

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 bash 命令在文件 2 中的特定字符串/文本之后将文件内容从文件 1 复制到文件 2 - bash command to copy file contents from file1 to file2 after particular string/text in file2 awk查找并在匹配时将变量file2替换为file1 - awk find and replace variable file2 into file1 when matched 从文件 2 中的文件 1 中找到最近的点,shell 脚本 - Find nearest point from file1 in file2, shell skript 将文件 1 中的字符串与文件 2 中的字符串匹配 - Match string in file1 with string in file2 Bash 检查 file1 行是否部分包含在 file2 的一行中 - Bash check if file1 line is partly contained in a line from file2 将File1与File2合并(继续从File1追加到File2,直到不再有行) - Merge File1 with File2 (keep appending from File1 to File2 until no more rows) 理解大括号对重定向的影响 (&quot;&gt; file1 &gt;&amp; file2&quot; vs. &quot;{ &gt; file1; } &gt;&amp; file2&quot;) - Understanding the effect of curly braces with respect to redirections ("> file1 >& file2" vs. "{ > file1; } >& file2") 是否可以使用 bash cmd 获取 file1 减去 file2 的内容? - is it possible to get the content of file1 minus file2 by using bash cmd? 使用sed和grep在file1中查找标题,并将内容移动到具有相同标题的file2 - use sed and grep to find title in file1 and move the content to file2 with same title Linux:将文件 1 中的字符 ID 分配给文件 2 的两列 f2_col1 和 f2_col2,而不更改文件 2 中的行顺序 - Linux: assigning character ids from file1 to two columns of file2, f2_col1 and f2_col2 without changing the row order in file2
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM