Linux 根据一个文件内容查找另一个文件中的内容

Linux awk About 1,082 words

案例

有文本1.txt,内容如下:

{"phone":"18633333333","code":"333333"}
{"phone":"18611111111","code":"111111"}
{"phone":"18655555555","code":"555555"}
{"phone":"18644444444","code":"444444"}
{"phone":"18622222222","code":"222222"}

有文本2.txt,内容如下:

18600000000
18633333333
18699999999
18611111111
18655555555

需求

找出1.txt中的phone字段是否在2.txt中,若存在,则输出完整的json串。

解决

方法一

遍历2.txt,逐行去1.txtgrep,输出到3.txt

cat 2.txt | while read line
do
grep $line 1.txt >> 3.txt
done

3.txt中内容:

{"phone":"18633333333","code":"333333"}
{"phone":"18611111111","code":"111111"}
{"phone":"18655555555","code":"555555"}

方法二(推荐)

由于博主之前清洗数据时两个文件都200多兆,使用while read line循环读取非常耗时。

  1. 使用awk合并两个文件
  2. :作为分隔符
  3. 逐行扫描,当ARGIND是文件1取分隔后的第四个元素作为key,整个一行原始字符串作为value,加入到awk数组(也可理解为map集合)
  4. 逐行扫描,当ARGIND是文件2时判断第一个元素是否存在数组中(awk判断的是key是否存在)
awk -F'"' '{if(ARGIND==1)phones[$4]=$0}{if(ARGIND>1 && ($1 in phones))print phones[$1]}' 1.txt 2.txt

输出:

{"phone":"18633333333","code":"333333"}
{"phone":"18611111111","code":"111111"}
{"phone":"18655555555","code":"555555"}

特别注意

需关注两个文件的文件格式,必须一致,否则会出现问题。

建议都转为unix编码格式。

可参考:不同平台文件格式:dos、unix、mac

Views: 8,791 · Posted: 2019-08-26

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh