tucuxi.org

Shell One-liners

(or not quite one-liners. Something to keep in your .profile, at least.)

Calculate a sum

This is often useful for du, wc or other such tools that provide a count per item, but don't provide a sum.

awk 'BEGIN { sum = 0; }; // { sum += $1; }; END { print sum }'

Calculate network throughput without vnstat

for f in 1 0; do
  /sbin/ifconfig eth1 |
  grep 'RX bytes' | \
      sed -r 's/^[^0-9]*:([0-9]*)[^:]*:([0-9]*).*/\1 \2/';
  sleep $f;
done | \
awk \
    'BEGIN { c = 0; rx = 0; tx = 0; };
    // { if (c) { print ($1 - rx) "b/s " ($2 - tx) "b/s" }; ++c; rx = $1; tx = $2; }'

CRAM-MD5 authentication

crammd5 () {
  CHALLENGE="$1"
  USER="$2"
  KEY="$3"
 
  echo "${USER} $(echo "${CHALLENGE}"|base64 -d|openssl dgst -md5 -hmac "${KEY}" -hex)"|base64
}

Calculate a CRAM-MD5 response when testing SMTP servers' AUTH CRAM-MD5 functionality. Takes a base64-encoded challenge, and returns a base64-encoded response.

git

alias git-diffsize='for i in *; do echo -e `git diff -U0 "${i}"|wc -l`"\t${i}"; done|grep -v "^0"|sort -n'

Find out how much has changed in each file in the current directory.

sed

sed -r '
  s/^([0-9]{2}:[0-9]{2}) /\[\1\] /;
  s/^(\[[0-9:]{5}] )<[ @&\+~]([^>]+)>/\1<\2>/;
  s/^--- Log opened /Session Start: /;
  s/^(\[[0-9:]{5}] )-!- [^ ]+ \[[^ ]+\] has joined (.*)$/\1* Now talking in \2/;
  s/^(\[[0-9:]{5}] ) (\*.*)$/\1\2/;
  s/^--- Log closed /Session Close: /;
  s/^(\[[0-9:]{5}\] )-!- mode\/[#&][^ ]+ \[([^]]+)\] by ([^ ]+)/\1\* \3 sets mode: \2/' \
  | egrep -v '^(\[[0-9:]{5}] )-!-'

Convert mIRC-style logs to irssi-style logs. Useful with mIRCStats and friends.

dpkg

dpkg-query -W -f'${Package}\t${Installed-Size}\t${Status}\n' | \
  awk '/[[:space:]]installed$/ { print $2 "\t" $1 }'

Find out how much space each package is using, du-style.