I want to grep for the string that starts with a dash/hyphen, like -X
, in a file, but it's confusing this as a command line argument.
I've tried:
grep "-X"
grep \-X
grep '-X'
I want to grep for the string that starts with a dash/hyphen, like -X
, in a file, but it's confusing this as a command line argument.
I've tried:
grep "-X"
grep \-X
grep '-X'
ARGS="-a -b -c"
grep -- "$ARGS"
–
Trinhtrini grep -- "--name awesome"
. –
Yod -X
followed by a space? (or a new line) –
Peasecod -i
) search for -std=
in my git repo. The following works: git grep -ni -- -std=
–
Dichroite The dash is a special character in Bash as noted at http://tldp.org/LDP/abs/html/special-chars.html#DASHREF. So escaping this once just gets you past Bash, but Grep still has it's own meaning to dashes (by providing options).
So you really need to escape it twice (if you prefer not to use the other mentioned answers). The following will/should work
grep \\-X
grep '\-X'
grep "\-X"
One way to try out how Bash passes arguments to a script/program is to create a .sh script that just echos all the arguments. I use a script called echo-args.sh to play with from time to time, all it contains is:
echo $*
I invoke it as:
bash echo-args.sh \-X
bash echo-args.sh \\-X
bash echo-args.sh "\-X"
You get the idea.
With GNU grep, grep -e -X
will do the trick.
-P
(but that is another story and does not apply here)). –
Dineric man grep
says about -e
: "This option can be used to protect a pattern beginning with “-”. –
Outwardbound grep -- -X
grep \\-X
grep '\-X'
grep "\-X"
grep -e -X
grep [-]X
I dont have access to a Solaris machine, but grep "\-X"
works for me on linux.
The correct way would be to use "--" to stop processing arguments, as already mentioned. This is due to the usage of getopt_long (GNU C-function from getopt.h) in the source of the tool.
This is why you notice the same phenomena on other command-line tools; since most of them are GNU tools, and use this call,they exhibit the same behavior.
As a side note - getopt_long is what gives us the cool choice between -rlo and --really_long_option and the combination of arguments in the interpreter.
If you're using another utility that passes a single argument to grep, you can use:
'[-]X'
None of the answers not helped me (ubuntu 20.04 LTS).
I found a bit another option:
My case:
systemctl --help | grep -w -- --user
-w
will match a whole word.
--
means end of command arguments (to mark -w
as not part of the grep
command)
grep "^-X" file
It will grep and pick all the lines form the file. ^ in the grep"^" indicates a line starting with
-
, not lines. –
Ott ls -l | grep "^-"
Hope this one would serve your purpose.
© 2022 - 2024 — McMap. All rights reserved.
--
means or does: unix.stackexchange.com/questions/11376/… – Caboose