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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With