Blazing fast grep alternative in Bourne shell

Software

I’ve always relied on Perl for sysadmin tasks, but I’ve been trying to get better at Bourne shell scripting. One operation I did constantly in Perl was searching for substrings:

#!/usr/bin/env perl
use strict;
use warnings;
my $string = "Zettai ryouiki";
my $sub    = "ryouiki";
print "Tousaka!" if ($line =~ m/substring/);

Until now I’d just been using grep, like a gentleman. If you’re network–bound and have a limited number of comparisons, it’s fine. Otherwise, it’s slow enough that even an i5 MacBook Air takes a moment between each operation.

#!/bin/sh
set -e
_string="Zettai ryouiki"
_sub="ryouiki"
[ `echo ${_string} | grep '${_sub}'` ] && echo "Tousaka!"

We can do better. An alternative is this neat trick, proposed by Matt Day on Stack Overflow:

if test "${_string#*$_sub}" != "${_string}"; then
    echo "Tousaka!"
fi

No pipes, no grep, just speed. Sugoi!

Author bio and support

Me!

Ruben Schade is a technical writer and infrastructure architect in Sydney, Australia who refers to himself in the third person. Hi!

The site is powered by Hugo, FreeBSD, and OpenZFS on OrionVM, everyone’s favourite bespoke cloud infrastructure provider.

If you found this post helpful or entertaining, you can shout me a coffee or send a comment. Thanks ☺️.