On 2022-05-28 at 17:11, Greg Wooledge wrote: > On Sat, May 28, 2022 at 04:02:39PM -0400, The Wanderer wrote: > >> On 2022-05-28 at 15:40, Jim Popovitch wrote: >> > I have a file of regex patterns and I use grep like so: >> > >> > ~$ grep -f patterns.txt /var/log/syslog >> > >> > What I'd like to get is a listing of all lines, specifically the line >> > numbers of the regexps in patterns.txt, that match entries in >> > /var/log/syslog. Is there a way to do this? >> >> I don't know of a standardized way to do that (if anyone else wants to >> suggest one, I'm open to learn), but of course it *can* be done, via >> scripting. Off the top of my head, I came up with the following >> >> for line in $(seq 1 $(wc -l patterns.txt | cut -d ' ' -f 1)) ; do >> if grep $(head -n $line patterns.txt | tail -n 1) /var/log/syslog > >> /dev/null ; then >> echo $line ; >> fi >> done > > The quoting here is... completely absent (and that's extremely bad), but > also importantly, one would ideally like to avoid running grep a thousand > times, especially if the target logfile is large. A brother of mine has schooled me on several things I did wrong here already, and I am now going over my long-tail stockpile of scripts with shellcheck, seeing what I can learn. (I normally do quote variables, but for some reason it slipped my mind this time until after I'd already hit Send. Some of these are known-safe values which won't need quoting, but others aren't, so the principle remains valid to cite.) This wasn't especially intended as a great solution, in any case; it started out as me trying to write shell-like pseudocode, but then I couldn't see any obvious reason why it wouldn't work, and when I tried it out I only needed a few tweaks before it did. There's a *reason* I had the "YMMV" on that message. -- The Wanderer The reasonable man adapts himself to the world; the unreasonable one persists in trying to adapt the world to himself. Therefore all progress depends on the unreasonable man. -- George Bernard Shaw
Attachment:
signature.asc
Description: OpenPGP digital signature