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?
To Show Lines That Exactly Match a Search String The grep command prints entire lines when it finds a match in a file. To print only those lines that completely match the search string, add the -x option. The output shows only the lines with the exact match.
The Backslash Character and Special Expressions The symbols \< and \> respectively match the empty string at the beginning and end of a word. The symbol \b matches the empty string at the edge of a word, and \B matches the empty string provided it's not at the edge of a word.
Use the ^ (caret) symbol to match expression at the start of a line. In the following example, the string kangaroo will match only if it occurs at the very beginning of a line. Use the $ (dollar) symbol to match expression at the end of a line.
If you include special characters in patterns typed on the command line, escape them by enclosing them in single quotation marks to prevent inadvertent misinterpretation by the shell or command interpreter. To match a character that is special to grep –E, put a backslash ( \ ) in front of the character.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With