问题
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 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)
来源:https://stackoverflow.com/questions/43579802/grep-lines-that-start-with-a-specific-string