Bash string padding with SED

technology.pngI know, I mentioned a bit of this earlier, but it deserves its own post.

You can left and right pad strings in BASH with spaces using SED. You do not have to use printf or anything else (despite what everyone else says).(Derived from instructions here, which talk more about centering than padding.)

This is the important part of the code:
Left justify with string length of 80
sed -e :a -e ‘s/^.{1,80}$/& /;ta’
Right justify with string length of 80
sed -e :a -e ‘s/^.{1,80}$/ &/;ta’
Center with string length of 80.
sed -e :a -e ‘s/^.{1,80}$/ & /;ta’

Popular posts:

  • Weekend Project: Whole House and Streaming Audio for Free with MPD
  • Minecraft Bug: Despawning Named Zombie Villagers
  • The difference between boundaries and rules
  • If there's one Nazi (or a racist) at the table...
  • Organizing and Tiling Your Windows on #Openbox Using Only... Openbox
  • Upgrading Voxelmap and Keeping Your Waypoints in #Minecraft
  • The Context of Abusive Statements

Recent Posts

4 Comments

  1. October 18, 2011

    Would it be possible to use this technique to convert from exponential notation to decimal?

    e.g convert 1.3e-2 ->0.013

  2. October 21, 2011

    Honestly, I have no idea. I often have to use a "try, try again" approach to SED.

    I'd think AWK might be a more useful tool for that, though – and perhaps a little easier to understand.

  3. tocororo-macho
    December 8, 2011

    Thanks for your post, I have crated a small function to make it reusable for scripting.

    function padding () {
    CONTENT="${1}"; PADDING="${2}"; LENGTH="${3}"; TRG_EDGE="${4}";
    case "${TRG_EDGE}" in
    left) echo ${CONTENT} | sed -e :a -e 's/^.{1,'${LENGTH}'}$/&'${PADDING}'/;ta'; ;;
    right) echo ${CONTENT} | sed -e :a -e 's/^.{1,'${LENGTH}'}$/'${PADDING}'&/;ta'; ;;
    center) echo ${CONTENT} | sed -e :a -e 's/^.{1,'${LENGTH}'}$/'${PADDING}'&'${PADDING}'/;ta'
    esac
    return ${RET__DONE};
    }

    Usage: echo "IP Address: padding "${IP_ADDRESS}" "${PADDING}" ${LENGTH}webserver";
    Hope you find it of any use.

  4. Beatrice Prose
    June 15, 2016

    In the end, I found this post !

    Thank YOU !

Comments are closed.