Friday, 30 May 2014

MessageFormat {0} for bash

Here is an sample string formatter written in bash, that works along the lines of the java string format class, see http://docs.oracle.com/javase/7/docs/api/java/text/MessageFormat.html.


#! /bin/bash
# Sam Liddicott sam@liddicott.com
# e.g. formatecho "Hello {1}, date of {0} is {0,datetime}, using '{0,datetime}'\n" 1401444493 "$USER"

cutstr() {
  printf -v "$1" "%s" "${4%%$3*}"
  printf -v "$2" "%s" "${4#"${!1}"}"
}

formatstr() {
  local target="$1"
  shift
  local format="$1"
  shift

  local result
  local start
  local arg
  local func

  # slice up to ' or { and process
  while test -n "$format"
  do cutstr start format "['{]" "$format"
     result="$result$start"
     case "$format" in
          {*) cutstr start format "}" "$format"
              format="${format:1}"
              cutstr arg start , "${start:1}"
              arg=$(( arg + 1 ))
              if test "${start:0:1}" = ","
              then result="$result"$(${start:1} "${!arg}")
              else result="$result${!arg}"
              fi
            ;;
        "'"*) format="${format:1}"
              cutstr start format "'" "$format"
              # empty string means ' but bash 4.2 errors stop me defaulting 
              # to ' or $'\x29' so I copy the ' from format
              result="$result${start:-${format:0:1}}"
              format="${format:1}"
            ;;
     esac
  done

  printf -v "$target" "$result"
}

formatecho() {
  local _message
  formatstr _message "$@"
  printf "%s" "$_message"
}

datetime() {
  date -d @"$@"
}

formatecho "$@"


No comments:

Post a Comment