-1

How would I use grep to compare if any line from one .txt document occurred in another?

Further how would I use grep to find out the opposite? Would it be grep -v?

3
grep -F -f inner_file outer_file

Explanation of the parameters from the documentation for GNU grep:

-F, --fixed-strings

Interpret the pattern as a list of fixed strings, separated by newlines, any of which is to be matched. (-F is specified by POSIX.)

-f file, --file=file

Obtain patterns from file, one per line. The empty file contains zero patterns, and therefore matches nothing. (-f is specified by POSIX.)

You might also want to use the -x option:

-x, --line-regexp

Select only those matches that exactly match the whole line. (-x is specified by POSIX.)

Add the -v option to find out the opposite:

-v, --invert-match

Invert the sense of matching, to select non-matching lines. (-v is specified by POSIX.)

Quick test using the Bash shell:

# grep -F -f <(printf 'A\nZ\n') <(printf 'A\nB\nC\n')
A
# echo $?
0
# grep -F -f <(printf 'A\nZ\n') <(printf 'B\nC\n')
# echo $?
1
# grep -v -F -f <(printf 'A\nZ\n') <(printf 'B\nC\n')
B
C
# echo $?
0
# grep -x -F -f <(printf 'A\nZ\n') <(printf 'AA\nBB\nCC\n')
# echo $?
1
1
  • 1
    Add the -x option if you want exact match as opposed to substring match. Jul 31 '14 at 20:23
1

I have tested something similar to your problem and concluded with this:

cat sampleOne.txt | cat sampleTwo.txt | grep <pattern>

For example I had this written in the text files:

This is a test.
1111
2222

When I looked specifically for "This is a test", I have used

cat *.txt | grep "This is a test."

This is a test.
This is a test.

or

cat sampleOne.txt && cat sampleTwo.txt | grep "This is a test."

Result:

This is a test.
11111
22222
This is a test.

or even

cat sampleOne.txt | cat sampleTwo.txt | grep "This is a test"

which got me:

This is a test.

The command grep -v pattern will of course find the inverse of the pattern you are looking for. For example

cat *.txt | grep -v "This is a test."

Will give me:

11111
22222
11111
22222
2
  • cat sampleOne.txt | cat sampleTwo.txt doesn't make sense because the first command (or better said the contents of sampleOne.txt) makes no difference. Jul 31 '14 at 20:58
  • I was experimenting with several commands that can be used. I wasn't too sure of cat sampleOne.txt | cat sampleTwo.txt though
    – ryekayo
    Jul 31 '14 at 21:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.