How can I grep for a string that begins with a das

2019-01-10 01:26发布

问题:

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'

回答1:

Use:

grep -- -X

Related: What does a bare double dash mean? (thanks to nutty about natty).



回答2:

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.



回答3:

grep -e -X will do the trick.



回答4:

grep -- -X
grep -- "-X"
grep  \\-X
grep  "\-X"
grep -e -X
grep [-]X


回答5:

I dont have access to a Solaris machine, but grep "\-X" works for me on linux.



回答6:

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.



回答7:

you can use nawk

$ nawk '/-X/{print}' file


回答8:

If you're using another utility that passes a single argument to grep, you can use:

'[-]X'


回答9:

ls -l | grep "^-"

Hope this one would serve your purpose.



回答10:

grep "^-X" file

It will grep and pick all the lines form the file. ^ in the grep"^" indicates a line starting with