简体   繁体   English

如果文件的列匹配,则AWK可以过滤文件

[英]AWK to filter to files if their columns match

I basically am working with two files (file1 and file2). 我基本上正在使用两个文件(文件1和文件2)。 The goal is to write a script that pulls rows from file1, if columns 1,2,3 match between files1 and files2. 目标是编写一个脚本,如果文件1、2中的1、2、3列匹配,则从文件1中提取行。 Here's the code I have been playing with: 这是我一直在玩的代码:

awk -F'|' 'NR==FNR{c[$1$2$3]++;next};c[$1$2$3] > 0' file1 file2 > filtered.txt

ile1 and file2 both look like this (but has many more columns): ile1和file2都看起来像这样(但有更多列):

name1 0 c 
name1 1 c
name1 2 x
name2 3 x
name2 4 c
name2 5 c

The awk code I provided isn't producing any output. 我提供的awk代码未产生任何输出。 Any help would be appreciated! 任何帮助,将不胜感激!

your delimiter isn't pipe, try this 您的定界符不是管道,请尝试此操作

$ awk 'NR==FNR {c[$1,$2,$3]++; next} c[$1,$2,$3]' file1 file2 > filtered.txt

or 要么

$ awk 'NR==FNR {c[$0]++; next} c[$0]' file1 file2 > filtered.txt

however, if you're matching the whole line perhaps easier with grep 但是,如果要匹配整行,则使用grep可能会更容易

$ grep -xFf file1 file2 > filtered.txt
awk '{key=$1 FS $2 FS $3} NR==FNR{file2[key];next} key in file2' file2 file1

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM