如何在shell中搜索包含括号和其他特殊字符的模式

时间:2015-06-27 22:34:55

标签: bash shell unix scripting grep

我正在尝试在“output2”文件中执行以下模式搜索,但即使grep命令的状态显示成功,它也不会提供所需的输出。

➜  automate git:(master) ✗ grep -F "@PreAuthorize("isFullyAuthenticated() and hasPermission(#updateStatus, 'MAX_LOAN_AMOUNT_FOR_APPROVE')")" output2
➜  automate git:(master) ✗ grep -nF "@PreAuthorize("isFullyAuthenticated() and hasPermission(#updateStatus, 'MAX_LOAN_AMOUNT_FOR_APPROVE')")" output2
➜  automate git:(master) ✗ echo $?
0
➜  automate git:(master) ✗ 

下面的output2文件的内容:

/home/workspace/OutputWithMessages.txt:1549:+ @PreAuthorize("isFullyAuthenticated() and hasPermission(#updateStatus, 'MAX_LOAN_AMOUNT_FOR_APPROVE')")
/home/workspace/OutputWithMessages.txt:3254:+ @PreAuthorize("isFullyAuthenticated() and hasPermission(#updateStatus, 'MAX_LOAN_AMOUNT_FOR_APPROVE')")
/home/workspace/OutputWithMessages.txt:4558:+ @PreAuthorize("isFullyAuthenticated() and hasPermission(#updateStatus, 'MAX_LOAN_AMOUNT_FOR_APPROVE')")
/home/workspace/OutputWithMessages.txt:5438:+ @PreAuthorize("isFullyAuthenticated() and hasPermission(#updateStatus, 'MAX_LOAN_AMOUNT_FOR_APPROVE')")
/home/workspace/OutputWithMessages.txt:5744:+ @PreAuthorize("isFullyAuthenticated() and hasPermission(#updateStatus, 'MAX_LOAN_AMOUNT_FOR_APPROVE')")
/home/workspace/OutputWithMessages.txt:6986:+ @PreAuthorize("isFullyAuthenticated() and hasPermission(#updateStatus, 'MAX_LOAN_AMOUNT_FOR_APPROVE')")
/home/workspace/OutputWithMessages.txt:7344:+ @PreAuthorize("isFullyAuthenticated() and hasPermission(#updateStatus,

2 个答案:

答案 0 :(得分:4)

需要正确引用字符串:

$ grep -F '@PreAuthorize("isFullyAuthenticated() and hasPermission(#updateStatus, '\''MAX_LOAN_AMOUNT_FOR_APPROVE'\'')")' output2
/home/workspace/OutputWithMessages.txt:1549:+ @PreAuthorize("isFullyAuthenticated() and hasPermission(#updateStatus, 'MAX_LOAN_AMOUNT_FOR_APPROVE')")
/home/workspace/OutputWithMessages.txt:3254:+ @PreAuthorize("isFullyAuthenticated() and hasPermission(#updateStatus, 'MAX_LOAN_AMOUNT_FOR_APPROVE')")
/home/workspace/OutputWithMessages.txt:4558:+ @PreAuthorize("isFullyAuthenticated() and hasPermission(#updateStatus, 'MAX_LOAN_AMOUNT_FOR_APPROVE')")
/home/workspace/OutputWithMessages.txt:5438:+ @PreAuthorize("isFullyAuthenticated() and hasPermission(#updateStatus, 'MAX_LOAN_AMOUNT_FOR_APPROVE')")
/home/workspace/OutputWithMessages.txt:5744:+ @PreAuthorize("isFullyAuthenticated() and hasPermission(#updateStatus, 'MAX_LOAN_AMOUNT_FOR_APPROVE')")
/home/workspace/OutputWithMessages.txt:6986:+ @PreAuthorize("isFullyAuthenticated() and hasPermission(#updateStatus, 'MAX_LOAN_AMOUNT_FOR_APPROVE')")

对于单引号,shell将单引号字符串中的所有字符视为文字字符除外)。要在字符串中输入单引号,请使用'\''

'\''分为三个步骤:首先使用'终止单引号字符串,然后添加带\'的转义单引号,最后启动一个新的单引号用'引用字符串。

答案 1 :(得分:0)

我替换了"用\"它解决了这个问题。

grep -F "@PreAuthorize(\"isFullyAuthenticated() and hasPermission(#updateStatus, 'MAX_LOAN_AMOUNT_FOR_APPROVE')\")" output2