gosatriani
gosatriani

Reputation: 307

how to compare 2 files in bash and redirect a specific value to a new file

I have a 2 files, say test and test1, with the following output:

test                      test1
abcd;india                abcd
efgh;india
ijkl;us
mnop;us

What's the correct way to compare test and test1 and and redirect the region information from test file to a new file say test2?

test2 expected output
india

Upvotes: 0

Views: 55

Answers (3)

James Brown
James Brown

Reputation: 37404

If test1 only has one entry, you could simplify:

$ awk -F\; -v p=$(<test1) '$1==p{print $2}' test
india    

Explained:

  • awk obvious
  • -F\; set the field separator
  • -v p=$(<test1) read the search word from file test1 to awk variable p
  • '$1==p{print $2}' if the search word is in the first field, print the second field
  • test the file

Upvotes: 0

gaurav goyal
gaurav goyal

Reputation: 1

you can use diff command to compare test and test1

diff test test1 > test2

Upvotes: 0

Akshay Hegde
Akshay Hegde

Reputation: 16997

awk -F';' 'FNR==NR{ a[$1]=$2; next }($1 in a){ print a[$1] }' test test1

To save in output file redirect like below

awk -F';' 'FNR==NR{ a[$1]=$2; next }($1 in a){ print a[$1] }' test test1 > test2

Explanation:

awk -F';' '                            # call awk set field separator as ;
           FNR==NR{                    # first file "test"
                a[$1]=$2;              # a is array, 
                                       # $1 (col1) is array key
                                       # $2 (col2) is array value
                next                   # stop processing further go to next line
           }
          ($1 in a){                   # here we read file "test1"
                                       # if array a has index which is 1st column from test1 file
                print a[$1]            # print array a value   
         }' test test1

Upvotes: 1

Related Questions