Grepping a fixed string at the beginning of a line

grep

grep "^$1" sort of works, but how do I escape "$1" so grep doesn't interpret any characters in it specially?

Or is there a better way?

Edit:
I don't want to search for '^$1' but for a dynamically inserted fixed string which should only be matched if it's at the beginning of a line. That's what I meant by the $1.

Best Answer

I can't think of a way to do this using grep; ^ itself is part of a regular expression so using it requires regular expressions to be interpreted. It's trivial using substring matching in awk, perl or whatever:

awk -v search="$1" 'substr($0, 1, length(search)) == search { print }'

To handle search strings containing \, you can use the same trick as in 123's answer:

search="$1" awk 'substr($0, 1, length(ENVIRON["search"])) == ENVIRON["search"] { print }'
Related Question