Hacker News new | ask | show | jobs
by JayGuerette 723 days ago
My pet peeve, grep unnecessarily followed by awk/sed.

Original: df -h | grep "$partition" | awk '{print $5}' | sed 's/%//'

Efficient: df -h | grep -Po "\d+(?=%\s+$partition)"

6 comments

Original is pretty readable. Efficient looks like what I get when I accidentally get shifted over to the right by one column.
FWIW, on ubuntu 22.04, your "Efficient" doesn't work

    # df -h | grep "$partition" | awk '{print $5}' | sed 's/%//'
    24
    # df -h | grep -Po "\d+(?=%\s+$partition)"
    #
Easiest to read is what I usually try optimize for, especially in a shell script.

I think the first one is much easier to read.

To be fair, if I needed something optimal or it was used often enough to matter, I'd probably reach for the original data in a real language. For a one-off, I can tell what grep/awk/sed does immediately - but I need to stop and think for the efficient solution.
Shouldn't the first one be `grep -F/--fixed-strings "${partition}"? The second example will break in any case where $partition contains special characters.
Yes, it's an easy fix though:

    df -h | grep -Po "\d+(?=%\s+\Q$partition\E)"
Oh cool, this is the first time I've heard of `grep \Q..\E'

https://stackoverflow.com/questions/54405892/are-q-and-e-sup...

Thanks!

At some point I should probably write an article about the 20k lines of bash and a little python that power my homelab and various automations. Bash isn't perfect but often 99% good enough is fine.

I would say the first way allows you to learn more tools that you can write one line CLIs with without digging through grep’s man page.