Home > front end >  fgrep for exact matches but -f file has substrings of other elements
fgrep for exact matches but -f file has substrings of other elements

Time:01-07

I have a weird fgrep problem that seems specific for Mac OS X (the unexpected behavior does not happen on Ubuntu Linux).

My file ("qlist") has these lines in it (with no spaces)

CMGC_CDK1
CMGC_CDK2
CMGC_CDK10

My file "biglist" has these lines in it:

CMGC_CDK1
CMGC_CDK10
CMGC_CDK11A
CMGC_CDK11B
CMGC_CDK12
CMGC_CDK13
CMGC_CDK14
CMGC_CDK15
CMGC_CDK16
CMGC_CDK17
CMGC_CDK18
CMGC_CDK19
CMGC_CDK2
CMGC_CDK20

I want to issue an fgrep command that gives me back only the exact matches (by line) of what's in qlist. I should get this:

fgrep -someflags -f qlist biglist

CMGC_CDK1
CMGC_CDK2
CMGC_CDK10

but the flags -x and -w don't give the expected result.

If I issue the command:

 fgrep -w -f qlist biglist

or

 fgrep -x -f qlist biglist

I get

CMGC_CDK1
CMGC_CDK2

What I expected (and wanted was):

CMGC_CDK1
CMGC_CDK10
CMGC_CDK2

It's as if the fact that the search item file ("qlist" in the command) has one line that is a substring of another (CMGC_CDK1, CMGC_CDK10) somehow suppresses using CMGC_CDK10 as a search item.

Note: on Ubuntu linux, I get the expected result. This seems specific for Mac OS X fgrep. I am doing this on Mac OS X, 10.15.1, in a Unix terminal window with the default installed fgrep.

What am I missing? How do I make this work?

Thanks, Roland

CodePudding user response:

Using GNU grep in macOS terminal it works as expected.

grep -w -f qlist biglist

My computer has GNU grep installed. You can easily install it by:

brew install grep

It will make your life easier as Mac user. You can also install coreutilities which allows you to use GNU versions of the commands on Mac terminal. You can still use macOS versions. This will also solve your cat command issue.

brew install coreutils

When I try to use fgrep this is the warning I get on macOS Terminal:

fgrep: warning: fgrep is obsolescent; using ggrep -F
CMGC_CDK1
CMGC_CDK10
CMGC_CDK2

Please note that ggrep simply refers to GNU grep in my system

  • Related