grep lines that start with a specific string

こ雲淡風輕ζ 提交于 2021-02-05 00:56:30

问题


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.

You don't want to make grep cry, do you?


回答1:


You should use awk instead of grep for non-regex search using index function:

awk -v s="$my_string" 'index($0, s) == 1' file

index($0, s) == 1 ensures search string is found only at start.




回答2:


What do you mean by if the Bash variable my_string contains ANY regular expression special characters, grep will cry

$ cat file
crying now
no cry
$ var="n.*"
$ echo "$var"
n.*
$ grep "^$var" file
no cry

Now that @anubhava spoon-fed me the problem (thank you sir), using grep for the job does seem to need at least two greps and since you want to grep the regex characters literally, use -F in the latter (or fgrep):

$ cat file
OMG it’s full of 
*s
$ var="*"
$ grep "^.\{"${#var}"\}" file|grep -F "$var"
*s

${#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.

(Quote from 2001)



来源:https://stackoverflow.com/questions/43579802/grep-lines-that-start-with-a-specific-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!