Grep that start with a specific line

I want to find all lines in a file that start with a specific line. The problem is that I do not know what the line is in advance. The value is stored in a variable.

A naive solution would be as follows:

grep "^${my_string}" file.txt; 

Because if the Bash my_string variable contains ANY special regular expression characters, grep will cry and everyone will have a bad day.

You don't want to shout grep , do you?

+5
source share
2 answers

You should use awk instead of grep to search without a regular expression using the index function:

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

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

+5
source

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

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

Now that @anubhava posed a problem for me (thank you sir), using grep for the job seems to need at least two grep , and since you want literal grep use regex characters, use -F in the last (or fgrep ):

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

${#var} returns the length of var in Bash, and this is the number of characters we extract from the beginning of the file to check with the last grep .

(Quote from 2001 )

0
source

Source: https://habr.com/ru/post/1267074/


All Articles