Shell script - entered input(1-40 bytes) needs to be converted exactly 40 bytes

hello,

suppose, entered input is of 1-40 bytes, i need it to be converted to 40 bytes exactly.

example: if i have entered my name anywhere between 1-40 i want it to be stored with 40 bytes exactly.

enter your name:
donald duck (this is of 11 bytes)

expected is as below - display 11 bytes entered and rest of the 29 bytes with blank space
donald duck____________________________(i refereed _ to blank space)

my shell script is something like below:

echo "enter you name"
read name
echo "enter age"
read age
echo $name$age

please help!

printf?

printf "%-40s" "Donald Duck"
1 Like

You do not mention the shell that you are using. In bash, the following would give the desired result:

$ read
$ printf -v name "%40s" "$REPLY"
$ echo "$name":
                             Donald Duck:

Use -40 for left justified text.

Thanks... it works.

i have another question - let's suppose i enter 41 chars, but i want first 40 chars to be read. can this be possible? please let me know.

echo "enter your name"
read name
printf "%-40s" "$name" (gives me 40 bytes) but here if i entered more than 40 chars it displays them all, but i need only first 40 chars.