bashvariables

Forced fixed variable length, can I do it easier than this?


I need to convert variable so it has exact length, if it's too short then extend it for spaces, it it's too long then cut it. E.g. for variable of 11 characters

$ var1=a
$ echo ${#var1}
1
$ var1=$(echo $var1 | sed 's/$/           /' | cut -c 1-11)
$ echo ${#var1}
11

While above works, it does not seem to be very handy for cases where I need long strings so I am looking for something more appropriate and elegant.


Solution

  • Use printf:

    formatted=$(printf "%11.11s" "$var1")
    

    Examples:

    printf "%11.11s\n" "a"
              a
    
    printf "%11.11s\n" "abcdefghijklmnop"
    abcdefghijk
    

    You can see it is making output exact 11 char long.