简体   繁体   中英

grep lines that start with a specific string

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?

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.

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 grep s 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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM