Home > Net >  How to compare content of one file to the another file in shell script line by line?
How to compare content of one file to the another file in shell script line by line?

Time:01-12

File 1 Content(TOp.txt) :

/
/boot
/home
/ptd
/ptd/tcd
/ptd/splunkforwarderdd

File 2 Content(POp.txt) :

/
/boot
/home
/ptd
/ptd/tcd
/ptd/apps/ddas

Output File 1(Op1.txt) :

/ptd/splunkforwarderdd

Output File 2(Op2.txt) :

/ptd/apps/ddas

Shell Script:

while read linesT; do
    TOp=$linesT
      while read linesP; do
         POp=$linesp
         if [[ "$TOp" == "$POp"  ]]; then        
         a=cool
         else 
         echo $TOp
         fi
     done < POp.txt
  done < TOp.txt

I did tried above code. But Its not working as expected.

I want TOp.txt file compare each line with each line in POp.txt file and shows the absent line from file TOp.txt as output.

Same for POp.txt file.

CodePudding user response:

You should read in single while, with different fd. But sort/diff will be much better

while read -u 3 linesT && read -u 4 linesP; do
  TOp=$linesT
  POp=$linesp
  if [[ "$TOp" == "$POp"  ]]; then
     a=cool
     else
     echo $TOp
  fi
done 3< TOp.txt 4< POp.txt

CodePudding user response:

Assuming the #lines of the two files are the same, would you please try the following:

#!/bin/bash

while IFS=$'\t' read -r top pop; do
    if [[ $top != $pop ]]; then
        echo "$top" >> Op1.txt
        echo "$pop" >> Op2.txt
    fi
done < <(paste <(sort TOp.txt) <(sort POp.txt))

The paste ... command merges two sorted files side by side then the variables $top and $pop are assigned to each lines.

[Edit]
If the lines of the two files are not balanced, it will be better to use the awk solution:

awk 'NR==FNR {t[$0]  ; next}                                    # memorize lines in "TOp.txt"
    {p[$0]  }                                                   # memorize lines in "POp.txt"
    END {
        for (i in t) if (p[i] == "") print i > "Op1.txt"        # lines only in "TOp.txt"
        for (i in p) if (t[i] == "") print i > "Op2.txt"        # lines only in "POp.txt"
    }
' TOp.txt POp.txt

CodePudding user response:

comm compares the lines of files

Interesting options:

   -1     suppress column 1 (lines unique to FILE1)

   -2     suppress column 2 (lines unique to FILE2)

   -3     suppress column 3 (lines that appear in both files)

   --nocheck-order
          do not check that the input is correctly sorted

Answer:

comm --nocheck-order -23 TOp.txt POp.txt > Op1.txt
comm --nocheck-order -13 TOp.txt POp.txt > Op2.txt
  •  Tags:  
  • Related