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.

Share:
12,342
Jonathan Matthews
Author by

Jonathan Matthews

Updated on June 14, 2022

Comments

  • Jonathan Matthews
    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
    anubhava about 7 years
    Problem is that using -F we cannot force grep to find match only at start of line.
  • James Brown
    James Brown about 7 years
    @anubhava Oh yeah, that is true. Good morning.
  • Silvia Justi
    Silvia Justi about 3 years
    what if I want to find the string at the beginning of the line, but I need the whole line to be printed?
  • anubhava
    anubhava about 3 years
    That's what this command does. Test it out
  • Silvia Justi
    Silvia Justi about 3 years
    Found my mistake!