Bash – fgrep beginning of line

bashgrepquoting

I'd like to use fgrep to handle searching literal words with periods and other meta-characters in grep, but I need to ensure the word is at the beginning of the line.

For example, fgrep 'miss.' will match miss. exactly which is what I want, but also admiss. or co. miss. which I don't want.

I might be able to escape meta-characters, e.g. grep '^miss\.', but the source is so large, I'm bound to miss something, and then need to run it again (will take the whole night). And in some cases, e.g. \1, the escaped code is the one with "meta-meaning".

Any way around this?

Best Answer

With GNU grep if built with PCRE support and assuming $string doesn't contain \E, you can do:

grep -P "^\Q$string"

With perl's rindex:

perl -sne 'print if rindex($_, $string, 0) == 0' -- -string="$string"

With awk:

S=$string awk 'index($0, ENVIRON["S"]) == 1'
Related Question