简体   繁体   English

在bash shell中使用grep在正则表达式中如何使用空格?

[英]How do spaces work in a regular expression with grep in the bash shell?

The way I would read the regular expression below: 我将阅读以下正则表达式的方式:

  1. a space char 一个空格字符
  2. a slash char 斜线字符
  3. a 'n' char 一个'n'char
  4. zero or more space chars 零个或多个空格
  5. end of line 行结束

But this test fails: 但是此测试失败:

$ echo "Some Text \n " | grep " \\n *$"

If I delete a space in the regular expression, does not fail 如果删除正则表达式中的空格,不会失败

$ echo "Some Text \n " | grep "\\n *$"
Some Text \n

Try this: 尝试这个:

echo "Some Text \n " | grep ' \\n *$'

Note the single quotes. 请注意单引号。 This serverfault question has more information about single vs. double quotes. serverfault问题具有有关单引号和双引号的更多信息。 With single quotes, the string is treated literally. 用单引号将字符串按字面意义处理。

Here's an explanation. 这是一个解释。 When you do: 当您这样做时:

echo "Test\\n" , you get Test\\n as the output, because echo doesn't translate the escape sequences (unless you send it the -e flag). echo "Test\\n" ,您将获得Test\\n作为输出,因为echo不会转换转义序列(除非您将其发送给-e标志)。

echo "Test\\n" | grep '\\n' echo "Test\\n" | grep '\\n' , it only matches the n . echo "Test\\n" | grep '\\n' ,仅匹配n This is because \\n is an "escaped n" (it doesn't seem to translate into an actual newline). 这是因为\\n是“转义的n”(它似乎没有转换为实际的换行符)。 If you want it to match the \\ and the n , you need to do echo "Test\\n" | grep '\\\\n' 如果要使其与\\n匹配,则需要执行echo "Test\\n" | grep '\\\\n' echo "Test\\n" | grep '\\\\n' . echo "Test\\n" | grep '\\\\n'

When using regular expressions you have to be mindful of the context in which you are using them. 使用正则表达式时,必须注意使用它们的上下文。 Several characters are treated specially by the regular expression engine, and also by the mechanism you use to invoke it. 几个字符由正则表达式引擎经过特殊处理的, 也可以通过该机制,你用它来调用它。

In your case you are using bash. 就您而言,您正在使用bash。 Depending on how you quote things you may have to escape special characters twice. 根据您引用事物的方式,您可能必须两次转义特殊字符。 Once to prevent bash from interpreting the special character and once again to get the regex behavior you desire. 一次阻止bash解释特殊字符,再一次获得您想要的正则表达式行为。

To solve problems like this you should first ask yourself "what must the expression look like?" 要解决这样的问题,您首先应该问自己“表达式必须是什么样?” You must then also ask, how must I prepare that expression so that the regular expression engine actually gets that pattern?" This involves understanding the effect that quoting has on the expression. Specifically in this case, the difference between single quote and double quotes (nd the other less comon quoting mechanisms). 然后,您还必须问,我应该如何准备该表达式,以便正则表达式引擎实际获得该模式?”,这涉及了解引用对表达式的影响。特别是在这种情况下,单引号和双引号之间的区别(以及其他不太常见的报价机制)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM