1

Let's say we have two files.

match.txt: A file containing patterns to match:

fed ghi
tsr qpo

data.txt: A file containing lines of text:

abc fed ghi jkl
mno pqr stu vwx
zyx wvu tsr qpo

Now, I want to issue a grep command that should return the first and third line from data.txt:

abc fed ghi jkl
zyx wvu tsr qpo

... because each of these two lines match one of the patterns in match.txt.

I have tried:

grep -F -f match.txt data.txt

but that returns no results.

grep info: GNU grep 2.6.3 (cygwin)
OS info: Windows 2008 R2

Update: It seems, that grep is confused by the space in the search pattern lines, but with the -F flag, it should be treating each line in match.txt as an individual match pattern.

2 Answers2

1

The solution to this is as follows:

Use the command: tr -d "\r" <match.txt | grep -F -f - text.txt

It seems that grep does not correctly respect windows line endings (CR/LF) for match files presented to it via the -f flag. The tr command can be used to strip carriage returns from the match file and the - special flag can be used with grep, to force it to read the match file from standard input.

  • Worth noting that in any typical git/hg version control workflow where you treat the pattern file as a text file and some users are on Windows, stripping carriage returns like this will be necessary to make it work. – Chiara Coetzee Apr 03 '19 at 21:12
0

Since it works on Unix, perhaps you need a later version of grep?

>cat d
abc fed ghi jkl
mno pqr stu vwx
zyx wvu tsr qpo

>cat p
fed ghi
tsr qpo

>grep -F -f p d
abc fed ghi jkl
zyx wvu tsr qpo

what happens if you change the patterns to

fed\040ghi
tsr\040qpo
RedGrittyBrick
  • 3,832
  • 1
  • 17
  • 23