Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grep lines that start with a specific string

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?

like image 454
Jonathan Matthews Avatar asked Apr 24 '17 04:04

Jonathan Matthews


People also ask

How do I grep for a specific string?

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.

How do you grep a string that is started with some string and ends with some string like a B?

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.

How do you grep at the beginning of a line?

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.

How do you grep a string with special characters in Unix?

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.


1 Answers

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.

like image 72
anubhava Avatar answered Oct 17 '22 22:10

anubhava