My Solution to the Last Elisp Challenge

The challenge was to convert the output from dstat so that all the bytes values (some of which are given as kilobytes or megabytes) to just bytes. Thus, 2k would become 2048 and 3M would become 3145728. Similarly, dstat outputs bytes with a B suffix so 123B would become 123.

Here’s my code:

(defun to-bytes ()
  (interactive)
  (while (search-forward-regexp "\\([0-9]+\\)\\(B\\|k\\|M\\)")
    (let ((val   (string-to-number (match-string 1)))
          (units (match-string 2)))
      (cond
       ((string= units "B") (replace-match "\\1"))
       ((string= units "k") (replace-match (format "%d" (* 1024 val))))
       ((string= units "M") (replace-match (format "%d" (* 1048576 val))))))))

It makes only one pass through the data so it’s reasonably efficient. Nothing earth shattering but it gives us a chance to keep our Elisp skills sharp.

This entry was posted in Programming and tagged , . Bookmark the permalink.