Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grep OR Operator Not Working

I need help with Unix. I am trying to see if one of two statements (printf and fprintf) are in a file. I used the command:

search=`cat $file | grep -w "fprintf\|printf"`

For some reason, it doesn't find either in files where one of those two exists. Why?

like image 675
Bryan Muscedere Avatar asked Oct 05 '12 03:10

Bryan Muscedere


People also ask

How do you force grep?

The \\ (double backslash) characters are necessary in order to force the shell to pass a \$ (single backslash, dollar sign) to the grep command. The \ (single backslash) character tells the grep command to treat the following character (in this example the $ ) as a literal character rather than an expression character.

Does grep fail if no match?

If there's no match, that should generally be considered a failure, so a return of 0 would not be appropriate. Indeed, grep returns 0 if it matches, and non-zero if it does not.

Does grep work in Linux?

Grep is an essential Linux and Unix command. It is used to search text and strings in a given file. In other words, grep command searches the given file for lines containing a match to the given strings or words. It is one of the most useful commands on Linux and Unix-like system for developers and sysadmins.


1 Answers

You have two problems.

First, standard grep doesn't support the | operator. You need to use egrep or the -E flag.

Second, inside double-quotes, \| means \|. The backslash gets passed through to the grep command, so even if grep understood the | operator, the backslash would turn it into a normal character.

Try this:

search=`cat $file | egrep -w "fprintf|printf"`

Or you can provide each alternative as a separate argument to grep:

search=`cat $file | grep -w -e fprintf -e printf
like image 170
rob mayoff Avatar answered Oct 06 '22 16:10

rob mayoff