We all have habits, and getting things done means that often we don’t look past them, or we’re not exposed to different ways of achieving something. Often I’ll sit back and think “actually let’s find another way of doing this”, or I see a cool trick and want to incororate it into my practice. Too often I don’t pass it on, or don’t practice it.
And so it goes with
grep for me, where I’ve never really looking into multiple matches. So I spent a small chunk of time to work it out.
Matching multiple patterns using egrep
I had just done one of these:
$ kubectl describe nodes|grep Taints Taints: <none> Taints: <none> $ kubectl describe nodes|grep Labels Labels: beta.kubernetes.io/arch=amd64 Labels: beta.kubernetes.io/arch=amd64
I can get the task done using this, and probably in not many more keystrokes, but what if I want these in a one-liner?
man grep and didn’t see anything obvious, except of course regular expresions, supported when passing
-E to grep, or otherwise just using
so when can use:
Going back to the original multi-grep we can do the following, and improve upon by also matching the Name field:
$ kubectl describe nodes | egrep '(^Name|aints|abels)' Name: k8smaster Labels: beta.kubernetes.io/arch=amd64 Taints: <none> Name: k8sworker1 Labels: beta.kubernetes.io/arch=amd64 Taints: <none>`
note I realised after this that it’s a bad example in practice as thekubectl command could be returning multiple rows of labels if more than one is present, and we’ll only match one. The method of multiple greps is still sound however.