How to use grep to search for a pattern which starts with a hyphen (-)?
sudo find / -name "*" | xargs grep -sn --color=auto "-j"
Above command returns below:
grep: invalid option -- 'j'
Usage: grep [OPTION]... PATTERN [FILE]...
Try `grep --help' for more information.
...
How do I search for string -j
?
In your case "-j"
is interpreted by grep
as an argument/option, not as a search pattern, even if you quoted it. To make it to be the pattern for what you want to search, just use -e
option:
sudo find / -name "*" | xargs grep -sn --color=auto -e "-j"
or even:
sudo find / -name "*" | xargs grep -sn --color=auto -e -j
The -e
argument/option means that the next argument is the pattern. This is from man grep
:
-e PATTERN, --regexp=PATTERN
Use PATTERN as the pattern. This can be used to specify
multiple search patterns, or to protect a pattern beginning with
a hyphen (-). (-e is specified by POSIX.)
Other ways:
use
--
, as @Rinzwind said in his answer, to makegrep
to hnow that the options ended.-
use
\
to escape the hyphen (-
):sudo find / -name "*" | xargs grep -sn --color=auto "\-j"
Tell it that the options ended with --
:
sudo find / -name "*" | xargs grep -sn --color=auto -- "-j"
Result:
Binary file /initrd.img matches
Binary file /lib/modules/2.6.24-16-server/ubuntu/media/gspcav1/gspca.ko matches
Binary file /lib/modules/2.6.24-16-server/ubuntu/sound/alsa-driver/isa/es1688/snd-es1688.ko matches
Binary file /lib/modules/2.6.24-16-server/ubuntu/sound/alsa-driver/pci/ice1712/snd-ice1712.ko matches
/lib/modules/2.6.24-16-server/modules.dep:1807:/lib/modules/2.6.24-16-server/kernel/fs/nls/nls_euc-jp.ko:
Binary file /lib/modules/2.6.24-16-server/kernel/crypto/blowfish.ko matches
Binary file /lib/modules/2.6.24-16-server/kernel/fs/nls/nls_euc-jp.ko matches
Binary file /lib/modules/2.6.24-16-server/kernel/fs/nls/nls_cp936.ko matches
You can escape -
character using \
$ sudo find / -name "*" | xargs grep -sn --color=auto "\-j"
Also you may want to exclude folders and search only files, add -type f
to find
:
$ sudo find / -name "*" -type f | xargs grep -sn --color=auto "\-j"
Also if you add -P 4
to xargs
, it will parallel all execution on 4 processes, and search may be done faster if you have more than 1 cores.
$ sudo find / -name "*" -type f | xargs -P 4 grep -sn --color=auto "\-j"