grep lines that start with a specific string
12,342
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.
Author by
Jonathan Matthews
Updated on June 14, 2022Comments
-
Jonathan Matthews almost 2 years
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? -
anubhava about 7 yearsProblem is that using
-F
we cannot forcegrep
to find match only at start of line. -
James Brown about 7 years@anubhava Oh yeah, that is true. Good morning.
-
Silvia Justi about 3 yearswhat if I want to find the string at the beginning of the line, but I need the whole line to be printed?
-
anubhava about 3 yearsThat's what this command does. Test it out
-
Silvia Justi about 3 yearsFound my mistake!