If you only need to check whether or not a match is found, cut all input lines to the length of the desired prefix ($1
) and then use fixed-pattern grep:
if cut -c 1-"${#1}" | grep -qF "$1"; then
echo "found"
else
echo "not found"
fi
It's also easy to get the count of matching lines:
cut -c 1-"${#1}" | grep -cF "$1"
Or the line numbers of all matching lines (line numbers start at 1):
cut -c 1-"${#1}" | grep -nF "$1" | cut -d : -f 1
You could feed the line numbers to head
and tail
to get the full text of the matching lines, but at that point it's easier to just reach for a modern scripting language like Python or Ruby.
(The above examples assume Posix grep and cut. They assume the file to search comes from standard input, but can easily be adapted to take a filename instead.)
Edit: You should also ensure that the pattern ($1
) is not a zero-length string. Otherwise cut
fails saying values may not include zero
. Also, if using Bash, use set -o pipefail
to catch error-exits by cut
.
grep '^$1'
? Or didn't you mean that you want to prevent the$1
being expanded by the shell?grep
too but you'll have to escape any special character in your string first e.g.printf %s ^;printf %s "$1" | sed 's/[][\.*^$]/\\&/g'; } | grep -f- infile