Blazing fast grep alternative in Bourne shell
SoftwareI’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!