Munu
Munu

Reputation: 135

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

File1 id.txt

101
102
103

File2 emp_details.txt

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

if the id of a.txt match with the first column of emp_details.txt then out put with full line to a new file matched.txt.If not matched then out put with only id to a new file notmatched.txt

example:

matched.txt

101 john USA
103 Alex USA

unmatched.txt (assumed by the editor)

102

Upvotes: 1

Views: 1102

Answers (4)

Rahul Verma
Rahul Verma

Reputation: 3089

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

Explanation:
use file1 as pattern to search in file2 and store matched results in matched file
use matched file's column1 as pattern to search in file1 and store non-matches in not_matched file
-v means "invert the match" in grep

Output :

$ cat matched
101 john USA
103 Alex USA

$ cat not_matched
102

Upvotes: 1

Akshay Hegde
Akshay Hegde

Reputation: 16997

Using awk:

One-liner:

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

Better Readable:

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

Test Results:

$ 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

Upvotes: 0

CWLiu
CWLiu

Reputation: 4043

It's an another thought compared to @Akshay Hegde's answer. Set the map for $1 and $0 in emp_details.txt into array 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

Upvotes: 0

Guenther
Guenther

Reputation: 2045

Usually we expect you to explain what you have tried and where you are stuck. We usually don't provide complete answers on this site. As it's just a few lines lines, I hacked up a not very efficient version. Simply loop over the id file and use egrep to find the matched and unmatched lines.

#!/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

Upvotes: 0

Related Questions