Using sed to match regexp patterns in a file with a fixed string (not the other way around)
Hi there!
Usually, sed can be used in different ways, but most of the time we use it to match lines in a file against a fixed regexp. Some examples:
This replaces ocurrences of regexp for "foo":
sed 's/regexp/foo/g' < myfile
This prints all lines that have "foo", but will change the first "o" in the line for an "a":
sed -n '/foo/s/o/a/p' < myfile
and so on...
But I tried to do a different thing, with no success: can I pass to sed a file with a bunch of regular expressions and test them against a fixed string? I tried to play with pattern space, hold space, with no success. It just seems impossible to use them (which would be the closest to "variables") in search commands.
I know sed is Turing complete, but using it that way would maybe require to implement a regexp engine from scratch?
Thanks!
5 replies
Yeah, I ended up using awk, which solved my problem perfectly. I was just curious if I could do that with sed, but it seems too complicated. Thank very much, guys!
Good call. I have no doubt sed could do it but I do doubt it in would be worth the time to figure it out vs just adding awk in there.
What result do you need? Do you just nedd to know if one of the regexps matched the string, or do you need to know which one, or is it something else?
I know you asked about sed, but in case grep is fine, too:
Not sure if there's an output which pattern matched.
IMO if you're doing something that complex you shouldn't be using
sed, but yeah you can probably do this something like:I strongly recommend you don't do that though. It will be absolutely full of quoting bugs. Instead write a script in a proper language to do it. I recommend Deno, or maybe even Rust.
If you use Rust you can also use
RegexSetwhich will be much faster (if you just want to find matches anyway). Here's what ChatGPT made me. Not tested but it looks vaguely right.