在Linux中如何使用grep搜索包含方括号("[]")的文本 [英] how to use grep to search for text containing square brackets("[ ]") in Linux

查看:438
本文介绍了在Linux中如何使用grep搜索包含方括号("[]")的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在文件中搜索包含"[]"括号的文本.例如

I am trying to searching a file to for text containing "[]" brackets. For example,

list[1];
i[ab1];

我尝试了 grep -i \ [[a-z || 1-9] * \] myfile .但这是行不通的.这些方括号是特殊字符.我不知道如何转义那里的特殊含义.有人可以提出任何建议吗?

I tried grep -i \[[a-z||1-9]*\] myfile. But it doesn't work. These square brackets are special characters. I don't know how to escaping there special meaning. Can anybody give any suggestion?

推荐答案

[是正则表达式中的特殊字符,因为它用于表示范围(就像您在子表达式 [az || 1-9] ).您需要转义,以便grep会将其解释为原义的 [字符;您可以在前面加上反斜杠来实现此目的.

[ is a special character in a regular expression, since it is used to denote a range (just as you use it for in the subexpression [a-z||1-9]). You need to escape it so that grep will interpret it as a literal [ character; you do this by preceeding it with a backslash.

但是,反斜杠也是外壳中的转义字符.要将单个反斜杠传递给grep,您需要在shell命令行上将其加倍!您还需要转义 | 字符,实际上应该转义 * 字符,因为这些字符对于shell也很特殊:

However, backslashes are also escape characters in the shell. To pass a single backslash to grep, you need to double it on the shell command line! You also need to escape the | characters and really should escape the * character, since these are also special to the shell:

grep -i \\[[a-z\|\|1-9]\*\\] myfile

如果只将整个字符串用双引号引起来,则会变得容易一些

It gets a bit easier if you just enclose the whole string in double quote marks:

grep -i "\\[[a-z||1-9]*\\]" myfile

请注意,您仍然需要将反斜杠加倍,因为它们也可以转义带引号的字符串中的字符.更好的方法是使用用引号引起来的字符串,其中反斜杠不能用作转义符:

Note that you still need to double the backslashes, as they can escape characters in a quoted string too. Even better would be to use a string enclosed with single quotes, in which backslashes don't act as an escape:

grep -i '\[[a-z||1-9]*\]' myfile

这篇关于在Linux中如何使用grep搜索包含方括号("[]")的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆