BASH - grep - works on command line, but not script
The problem seems to reside in your regex. can you show us what you are trying to match?
if you are trying to match constructs like this :
this.contentOfVar
contentOfVar
try it with the following :
grep -cP "(this\.|\s)$VARIABLE_NAME" $FILE_PATH
This works in GNU grep.
You don't have to specify {1}
, since the default will be 1.
With the -P
flag on, \(
and \)
will match literal parenthesis in the string, since this is the perl behavior.
Related videos on Youtube
Walter
Updated on September 18, 2022Comments
-
Walter over 1 year
I am trying to get the number of occurrences in a script and when running the command on the command line, it works fine, but not in a script. Both variables are initialized. FILE_PATH is the absolute path of the file and VARIABLE_NAME is something like firstName or lastName.
VARIABLE_NAME="_firstName" grep -cP "\(this\.|\s\){1}$VARIABLE_NAME" $FILE_PATH
When I take $VARIABLE_NAME out of the script and replace it directly with what I am looking for, it works as expected, so it is something with the replacement.
Any ideas what I can try?
-
garyjohn almost 13 yearsIs that really all that line does in your script, print the number of occurrences to stdout, or is it part of some larger command?
-
Walter almost 13 yearsIt is part of a larger command, but I cannot get this part to work.
-