LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   printf white space issue word splitting (https://www.linuxquestions.org/questions/linux-newbie-8/printf-white-space-issue-word-splitting-814295/)

dukedog 06-15-2010 11:55 AM

printf white space issue word splitting
 
I am having trouble keeping the name together and the phone number together, I think due to the white space. I have tryed "" and '' it doesn' seem to matter. So it may be my syntax? and does it matter how long the first and last names are.


me$ echo 'fstname lstname' '123 123-1234' | ./myscript


#myscript
read a b
printf "%-15s %20s\n" $a $b >> my_phone_numbers

OUTPUT

fstname lstname
123 123-1234
insted of
fstname lstname 123 123-1234

i know its not an elegant script but im still learning how some commands work

thanks to the people who help on this site it has helped many times in the past

David the H. 06-15-2010 12:36 PM

The need for quoting on the command line is a separate issue from the word splitting done inside the script. They're necessary to keep the input strings together when sending the values to the script, but they're not part of the input itself.

Inside the script you have to reapply the quotes wherever you need the spaces to be seen as part of the string, around variable references in particular.
Code:

read a b
printf "%-15s %20s\n" "$a" "$b" >> my_phone_numbers

Edit: I just noticed that there's a second issue here as well. The quotes in the input line only protect the input long enough to pass the values to echo; then it's echo that pipes them into the script. This means that the spaces are NOT protected when they hit read. You can check it yourself:
Code:

read a b
echo "a is $a"
echo "b is $b"
printf "%-15s %20s\n" "$a" "$b" >> my_phone_numbers

...and the output:
Code:


$ echo 'fstname lstname' '123 123-1234' | ./myscript
a is fstname
b is lstname 123 123-1234
firstname      lastname 123 123-1234

The only way I know to overcome that, as long as you use echo and a pipe, is to escape the spaces in order to protect them from echo.
Code:

$ echo -e "fstname\ lstname" "123\ 123-1234" | ./myscript
a is fstname lstname
b is 123 123-1234
firstname lastname        123 123-1234


dukedog 06-15-2010 01:46 PM

thanks again for all the help, That did the trick


All times are GMT -5. The time now is 12:08 PM.