Any #regex and #grep gurus able to help me understand something? I'm not the best with regex, trying to learn.

https://regex101.com/r/iHvpcJ/1

I'm trying to return the powered state of the wifi device from connman output. It seems like what I have here in regex101 should be returning the true or false state, but when I try to use the regex with grep I'm getting a warning:

`grep: warning: stray \ before N`

I'm struggling to figure out what I need to change to make it work with grep.

regex101: build, test, and debug regex

Regular expression tester with syntax highlighting, explanation, cheat sheet for PHP/PCRE, Python, GO, JavaScript, Java, C#/.NET, Rust.

regex101

@finner I'm not sure this can be done with grep. The first issue is that your selected regex flavor on regex101 is "PCRE2", but grep uses ... well, grep-flavored regexes by default (also known as "POSIX basic" regexes). grep does not directly support look-behind, non-greedy quantifiers, \N, or the s flag. The second issue is that grep matches each line separately, so it will never find a match that spans multiple lines.

The first issue could be mitigated if you're using GNU grep, which has a -P switch to enable PCRE2 support, but I don't see how to get past the second issue.

@finner Here's a solution using perl instead:

perl -wlne 'if (m{/wifi} ... m{^/}) { print $1 if /\bPowered = (\S+)/ }'

(Translation to awk is left as an exercise for the reader.)

#perl #awk

@barubary @finner for an #awk version:

awk '/^\//{s=0}/wifi$/{s=1}s && $1=="Powered"{print $NF; exit}'

(if there's more than one wifi device and you want *all* of the Powered= values rather than just the first wifi device, you can remove the "; exit")

@gumnos @barubary

Thanks, I'm going to play around with some of these suggestions later and see which I think works best for me.

Awk is another utility that I've only looked at briefly before and do not have a lot of experience with. I love how when you start learning some of these *nix utilities there are so many things you're about to do so easily when you get good with them.

I really should have built better awk and regex skills a long time ago.

@finner @gumnos I went from bash basics straight to perl, so I never learned (or missed) sed and awk. But if you want something really weird (and rarely used by anyone), check out m4.

@barubary @gumnos

Sed is another one I'm aware of but not very familiar with.

M4 I have definitely never heard of. Haha. I'll have to take a look.

@finner

m4(1) is surprisingly useful for preprocessing and templating. It's also often available as part of base installs (such as my FreeBSD & OpenBSD machines) without having to install anything. And it has been part of the compiler-toolchain-plumbing for decades. ☺

(that said, I don't use it often, but I have jabbed at it occasionally out of experimentation)

@barubary

*edit: forgot verb*