fgrep beginning of line?

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'

If your data is very large, then grep is likely to be faster than more flexible tools such as awk. What I'd do is to quote the special characters in the text and call grep.

pattern=$(printf '%s\n' "$literal_text" | sed 's/[\[.*^$]/\\&/g')
grep "^$pattern" my-big-file

If the text only contains ASCII characters, set the character set to C, so that grep only concerns itself with bytes. In some implementations (such as many versions of GNU grep), multi-byte characters can cause a significant speed penalty.

LC_CTYPE=C grep "^$pattern" my-big-file

If you want to search an exact whole line, then there's an option for that: grep -Fx -e "$literal_text". But this only matches lines that consist of exactly the specified text, there's no similar way to match lines that start with the specified text.


with awk

awk -vword='miss.' 'index($0, word) == 1' file

For multiple words

awk 'BEGIN{for (i=2; i<ARGC; ++i)word[++j]=ARGV[i]; ARGC=2}
    {for (i=1; i<=j; ++i)if (index($0, word[i]) == 1){print; continue}}' file \
    word1 word2 word3

I also fancy python for this

python3 -c 'import sys
words = tuple(sys.argv[1:])
for line in sys.stdin:
  print(line if line.startswith(words) else "", end="")
' <file word1 word2 word3 

Tags:

Bash

Grep

Quoting