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

I"m a big fan and post about #awk frequently¹, blog about it occasionally², and hang out in r/awk too. The hashtag is also worth following if you aspire to use it more.

@barubary


¹ https://mastodon.bsd.cafe/search?q=awk+from%3Agumnos&type=statuses

² https://blog.thechases.com/categories/awk/

³ https://www.reddit.com/r/awk/

BSD.cafe Mastodon Portal

Welcome to the BSD Cafe! We're excited to serve you the best flavors of BSD, including FreeBSD, NetBSD, OpenBSD, and DragonflyBSD. But if you prefer Linux, you're welcome here too!

Mastodon hosted on bsd.cafe