Blazing fast grep alternative in Bourne shell

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!


Imprint

This is one of about 5000 posts on Rubénerd. View the home page for the latest, or related posts also tagged with:

If you liked this post, feel free to buy me a coffee, leave me a comment on Twitter, or email me at weblog2017@rubenschade.com. Thanks :).