本文翻译自:How can I grep for a string that begins with a dash/hyphen?
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. 我想在文件中grep输入以破折号/连字符开头的字符串,例如-X
,但这将其混淆为命令行参数。
I've tried: 我试过了:
grep "-X"
grep \-X
grep '-X'
#1楼
参考:https://stackoom.com/question/ABbt/如何对以破折号-连字符开头的字符串进行grep
#2楼
The dash is a special character in Bash as noted at http://tldp.org/LDP/abs/html/special-chars.html#DASHREF . 如http://tldp.org/LDP/abs/html/special-chars.html#DASHREF所述,破折号是Bash中的特殊字符。 So escaping this once just gets you past Bash, but Grep still has it's own meaning to dashes (by providing options). 因此,一次转义就可以使您摆脱Bash的困扰,但是Grep仍然具有破折号的含义(通过提供选项)。
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. 尝试Bash如何将参数传递给脚本/程序的一种方法是创建一个仅回显所有参数的.sh脚本。 I use a script called echo-args.sh to play with from time to time, all it contains is: 我不时使用名为echo-args.sh的脚本进行播放,它包含的所有内容是:
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楼
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. 这是由于在该工具的源代码中使用了getopt_long(来自getopt.h的GNU C函数)。
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. 由于大多数都是GNU工具,并且使用此调用,因此它们表现出相同的行为。
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. 附带说明-getopt_long是让我们在-rlo和--really_long_option之间以及在解释器中的参数组合之间进行酷炫选择的原因。
#4楼
grep -e -X
可以解决问题。
#5楼
Use: 采用:
grep -- -X
Related: What does a bare double dash mean? 相关: 裸双破折号是什么意思? (thanks to nutty about natty ). (感谢有关natty的坚果 )。
#6楼
我没有访问Solaris机器的权限,但是grep "\\-X"
在Linux上对我有效。