Bourne Shell Left Right Justify

前端 未结 6 1130
情深已故
情深已故 2020-12-18 14:31

I am trying to do some formatting on output data in a script and not positive how to do Left Right justify as well as width. Can anyone point me in the right direction?

6条回答
  •  猫巷女王i
    2020-12-18 15:14

    You can do it using pure bash:

    x="Some test text"
    width="                    "      # 20 blanks
    echo "${width:0:${#width}-${#x}}$x"
    

    Output is:

    '      Some test text'             (obviously without the quotes)
    

    So the two things you need to know is ${#var} will get the length of the string in var, and ${var:x:y} extracts a string from x to y positions.

    You may need a recent version (tested on GNU bash 3.2.25)

    EDIT: Come to think of it, you can do it like this:

    echo "${width:${#x}}$x"
    

提交回复
热议问题