sed-awk-cheatsheet icon indicating copy to clipboard operation
sed-awk-cheatsheet copied to clipboard

Portability beyond Linux and Bash

Open Veraellyunjie opened this issue 2 years ago • 1 comments

In case your cheatsheet is not meant to be specific to Linux and Bash, 2 of https://github.com/codenameyau/sed-awk-cheatsheet#useful-commands I tried need attention.


# Kills all processes by name.
ps aux | grep chrome | awk '{ print $2 }' | kill

I get usage message from kill as it doesn't accept PIDs from STDIN. I would rewrite the command like this:

ps axww -o pid,command | awk '$2 ~ /^chrome/ { system("kill " $1) }'
  • ww makes output wide - it doesn't truncate lines to the window width
  • we remove u but specify -o pid,command so that ps reports only the data we are after
  • we need not grep - awk can do the job alone
  • we need not pipe as awk can run kill via system

# Generate random numbers and then sort.
for i in {1..20}; do echo $(($RANDOM * 777 * $i)); done | sort -n

.. isn't built-in everywhere. I get sh: 16398 * 777 * {1..20}: unexpected {'` It might be tempting to write:

for i in $(seq 20); do echo $(($RANDOM * 777 * $i)); done | sort -n

but seq isn't available everywhere either. And since we are at awk cheatsheet:

awk 'BEGIN { for (i=1; i<=20; i++) print int(rand() * 777 + 1) }' | sort -n

The above command will print sorted random numbers from 1 to 777. Frankly, I didn't understand why you may want to multiply by $i, so I omitted it.

Regards

Veraellyunjie avatar Feb 06 '23 12:02 Veraellyunjie