top | item 40723747

(no title)

JayGuerette | 1 year 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)"

discuss

order

bee_rider|1 year ago

Original is pretty readable. Efficient looks like what I get when I accidentally get shifted over to the right by one column.

upon_drumhead|1 year ago

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)"
    #

spicyusername|1 year ago

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.

viraptor|1 year ago

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.

metadat|1 year ago

Shouldn't the first one be `grep -F/--fixed-strings "${partition}"? The second example will break in any case where $partition contains special characters.

oguz-ismail|1 year ago

Yes, it's an easy fix though:

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

EasyMark|1 year ago

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.