5 ms·
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+(?=
by JayGuerette 2y 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)"
- metadat 2y agoShouldn'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 2y agoYes, it's an easy fix though: df -h | grep -Po "\d+(?=%\s+\Q$partition\E)"
- metadat 2y agoOh cool, this is the first time I've heard of `grep \Q..\E' https://stackoverflow.com/questions/54405892/are-q-and-e-supposed-to-escape-the-delimiter-in-pcre 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.
- viraptor 2y agoTo 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.
- upon_drumhead 2y agoFWIW, 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 2y agoEasiest to read is what I usually try optimize for, especially in a shell script. I think the first one is much easier to read.
- bee_rider 2y agoOriginal is pretty readable. Efficient looks like what I get when I accidentally get shifted over to the right by one column.
- EasyMark 2y agoI 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.