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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 16:03:25  来源:igfitidea点击:

grep lines that start with a specific string

regexstringbashawkgrep

提问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_stringcontains ANY regular expression special characters, grepwill cry, and everyone will have a bad day.

因为如果 Bash 变量my_string包含 ANY 正则表达式特殊字符,grep会哭,每个人都会有不好的一天。

You don't want to make grepcry, do you?

你不grep想哭,是吗?

采纳答案by anubhava

You should use awkinstead of grepfor non-regex search using indexfunction:

您应该使用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) == 1ensures search string is found only at start.

index($0, s) == 1确保仅在开始时找到搜索字符串。

回答by James Brown

What do you mean by if the Bash variable my_stringcontains ANY regular expression special characters, grepwill cry

如果 Bash 变量包含任何正则表达式特殊字符,你是什​​么意思会哭my_stringgrep

$ 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 grepfor the job does seem to need at least two greps and since you want to grepthe regex characters literally, use -Fin the latter (or fgrep):

现在@anubhava 用勺子给我解决了这个问题(谢谢先生),grep用于这项工作似乎确实需要至少两个greps,并且由于您想要grep字面上的正则表达式字符,请-F在后者(或fgrep)中使用:

##代码##

${#var}returns varlength in Bash and that amount of chars we extract from the beginning of file to be examined with the latter grep.

${#var}返回varBash 中的长度以及我们从文件开头提取的字符数量,以供后者检查grep

(Quote from 2001)

(引自2001 年