繁体   English   中英

如果字符串与 unix shell 脚本中的另一个文件匹配,则打印文件的完整行

[英]print the full line of the file if a string matched from another file in unix shell scripting

文件 1 id.txt

101
102
103

File2 emp_details.txt

101 john USA
103 Alex USA
104 Nike UK
105 phil UK

如果 a.txt 的 id 与 emp_details.txt 的第一列匹配,则将整行输出到新文件 match.txt。如果不匹配,则仅将 id 输出到新文件 notmatched.txt

例子:

匹配.txt

101 john USA
103 Alex USA

unmatched.txt(由编辑器假设)

102
grep -f f1 f2 > matched  
grep -vf <(awk '{print $1}' matched) f1 > not_matched

解释:
使用file1作为模式在file2搜索并将匹配的结果存储在matched文件中
使用matched文件的 column1 作为模式在file1搜索并将非匹配项存储在not_matched文件中
-v在 grep 中表示“反转匹配”

输出

$ cat matched
101 john USA
103 Alex USA

$ cat not_matched
102

通常我们希望您解释您尝试过的内容以及您遇到的问题。 我们通常不会在本网站上提供完整的答案。 由于只有几行,我编写了一个效率不高的版本。 只需遍历 id 文件并使用 egrep 查找匹配和不匹配的行。

#!/bin/bash

while read p; do
  egrep "^$p" emp_details.txt >> matched.txt
done <id.txt

while read p; do
  if ! egrep -q "^$p" emp_details.txt; then
    echo $p >> unmatched.txt;
  fi
done <id.txt

使用awk

单线:

awk 'FNR==NR{ arr[$1]; next }($1 in arr){ print >"matched.txt"; delete arr[$1] }END{for(i in arr)print i >"unmatched.txt"}' file1 file2

更好的可读性:

awk '
        FNR==NR{ 
                 arr[$1]; 
                 next 
        }
        ($1 in arr){ 
               print >"matched.txt"; 
               delete arr[$1]
        }
        END{
               for(i in arr)
                  print i >"unmatched.txt"
        }
    ' file1 file2

检测结果:

$ cat file1
101
102
103

$ cat file2
101 john USA
103 Alex USA
104 Nike UK
105 phil UK

$ awk 'FNR==NR{arr[$1];next }($1 in arr){print >"matched.txt";delete arr[$1]}END{for(i in arr)print i >"unmatched.txt"}' file1 file2

$ cat matched.txt 
101 john USA
103 Alex USA

$ cat unmatched.txt 
102

与@Akshay Hegde 的回答相比,这是另一个想法。 将 emp_details.txt 中$1$0的映射设置为数组a

awk 'NR==FNR{a[$1]=$0;next} {if($1 in a){print a[$1]>>"matched.txt"}else{print $1 >> "unmatched.txt"}}' emp_details.txt id.txt

暂无
暂无

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

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