bash 以特定字符串开头的 grep 行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43579802/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
grep lines that start with a specific string
提问by Jonathan Matthews
I want to find all the lines in a file that start with a specific string. The problem is, I don't know what's in the string beforehand. The value is stored in a variable.
我想查找文件中以特定字符串开头的所有行。问题是,我事先不知道字符串中的内容。该值存储在一个变量中。
The na?ve solution would be the following:
天真的解决方案如下:
grep "^${my_string}" file.txt;
Because if the Bash variable my_string
contains ANY regular expression special characters, grep
will cry, and everyone will have a bad day.
因为如果 Bash 变量my_string
包含 ANY 正则表达式特殊字符,grep
会哭,每个人都会有不好的一天。
You don't want to make grep
cry, do you?
你不grep
想哭,是吗?
采纳答案by anubhava
You should use awk
instead of grep
for non-regex search using index
function:
您应该使用awk
而不是grep
使用index
函数进行非正则表达式搜索:
awk -v s="$my_string" 'index($ cat file
crying now
no cry
$ var="n.*"
$ echo "$var"
n.*
$ grep "^$var" file
no cry
, s) == 1' file
index($0, s) == 1
ensures search string is found only at start.
index($0, s) == 1
确保仅在开始时找到搜索字符串。
回答by James Brown
What do you mean by if the Bash variable my_string
contains ANY regular expression special characters, grep
will cry
如果 Bash 变量包含任何正则表达式特殊字符,你是什么意思,会哭my_string
grep
$ cat file
OMG it's full of
*s
$ var="*"
$ grep "^.\{"${#var}"\}" file|grep -F "$var"
*s
Now that @anubhava spoon-fed me the problem (thank you sir), using grep
for the job does seem to need at least two grep
s and since you want to grep
the regex characters literally, use -F
in the latter (or fgrep
):
现在@anubhava 用勺子给我解决了这个问题(谢谢先生),grep
用于这项工作似乎确实需要至少两个grep
s,并且由于您想要grep
字面上的正则表达式字符,请-F
在后者(或fgrep
)中使用:
${#var}
returns var
length in Bash and that amount of chars we extract from the beginning of file to be examined with the latter grep
.
${#var}
返回var
Bash 中的长度以及我们从文件开头提取的字符数量,以供后者检查grep
。
(Quote from 2001)
(引自2001 年)