You can do it. But it is a really, really bad idea. It will be far slower (as in orders of magnitude slower) than grep
and less portable since it depends on features of a specific shell (Bash).
This would print out lines matching a regex pattern given as the first argument, similarly to grep pattern
:
#!/bin/bash -
regexp="$1"
ret=1
while IFS= read -r line || [ -n "$line" ]; do
if [[ $line =~ $regexp ]]; then
printf '%s\n' "$line"
ret=0
fi
done
exit "$ret"
Save that as foo.bash
and run like this:
foo.bash pattern < inputFile
Or using standard sh
syntax, looking for a fixed string and not a regex:
#!/bin/sh -
string="$1"
ret=1
while IFS= read -r line || [ -n "$line" ]; do
case $line in
("$string")
printf '%s\n' "$string"
ret=0
esac
done
exit "$ret"
(Replace the printf
with exit 0
to get behaviour similar to grep -q
.)
Just to give you an idea of how slow it is, I created a file with just 10001 lines, the first 5000 being foo
, then a single bar
and then another 5000 foo
:
perl -e 'print "foo\n" x 5000; print "bar\n"; print "foo\n" x 5000;' > file
Now, compare the times for grep
and the script above:
$ time grep bar < file
bar
real 0m0.002s
user 0m0.002s
sys 0m0.000s
$ time ./foo.bash bar < file
bar
real 0m0.116s
user 0m0.101s
sys 0m0.016s
As you can see, even with this tiny file, the difference is noticeable. If we try with a more substantial one, the time the script takes turns almost unbearable:
$ perl -e 'print "foo\n" x 500000; print "bar\n"; print "foo\n" x 500000;' > file
$ time grep bar < file
bar
real 0m0.004s
user 0m0.000s
sys 0m0.004s
$ time ./foo.bash bar < file
bar
real 0m11.306s
user 0m10.117s
sys 0m1.188s
However, this is partly because Bash is slow. The standard sh version runs a bit faster with Dash:
$ time dash foo2.sh bar < file
bar
real 0m3.467s
user 0m2.113s
sys 0m1.353s
However, it's still a difference of three orders of magnitude. Multiple seconds for the scripts, against the near-instant grep
. And this is still a file with only a million lines and ~4MB in size. I hope you see the problem...
compress
, and Busybox probably could help too.) Of course, even if not silly, esp. doing compression in the shell would be totally hideous. – ilkkachu Mar 23 '21 at 19:43