adjusting string var to fixed length

Jerry Peek jerry at ora.com
Sat Jun 8 18:45:07 AEST 1991


In article <190 at atesysv.UUCP> lanzo at atesysv.UUCP (Mark Lanzo) writes:
> In a prior article rchattam at isis.cs.du.edu (King Chattam) wrote:
>       I have a shell var (length 0 to 10), which I want always to be output
>     to a file as fixed length 10. I tried sed, awk etc to adjust the string
>     length to 10, but did not work.
>     
>       Could someone please tell me how blanks can be appended to string vars
>     to make it fixed length?
	...
> If you are using "sh" or "csh", then it's going to be harder as there isn't
> anything built-in to the shell to do it for you.

Mark probably didn't mention this built-in because it's sorta ugly. ;-)
But I've used "case" for all kinds of things.  It's built in to the
shell, so it often runs faster than starting a process like expr or awk
(expecially awk!) to do the same thing in a cleaner-looking way.
Here goes... hold your nose... :-)

	case "$var" in
	"") var="          " ;;
	?) var="$var         " ;;
	??) var="$var        " ;;
		...etc...etc...
	?????????) var="$var " ;;
	??????????) ;; # not needed unless you also use the *) below
	*) # add code here if you want to do handle too-long $var ;;
	esac

--Jerry Peek, O'Reilly & Associates
  jerry at ora.com or uunet!ora!jerry



More information about the Comp.unix.shell mailing list