replacing single space in argument

I want to write a script which will check the arguments and if there is a single space(if 2 more more space in a row , then do not touch), replace it with _ and then gather the argument

so, program will be ran

./programname  hi    hello hi    usa  now  hello hello

so, inside of program, after going through my little script, it should come out as

$1 = hi
$2 = hello_hi
$3 = usa
$4 = now
$5 = hello_hello

It's rather diffuclt for me since I am not sure even if I got rid of space and replace it with _, not sure how to assign back to correct positional parameters..

to input arguments with spaces, on the command line use double quotes
eg

# ./script arg1 "hello test" blah blah

I am trying to run it so that user don't have to quote anything when they put argument(often times, it will be copy and paste)

To simplify, pass everything as 1 quoted argument, then have the script process it, e.g.

$ cat > space_parsing
#!/bin/bash

set -- $( echo "$1" | sed 's/\([^ ]\) \([^ ]\)/\1_\2/g' | tr -s ' ' )

echo "$@"

echo "$1"

echo "$4"

exit 0
^D
$ chmod +x !$
chmod +x space_parsing
$ ./space_parsing "foo    bar    baz    hello hi    foo   hello hi again"
foo bar baz hello_hi foo hello_hi_again
foo
hello_hi

Cheers,
ZB

You cannot do that. Your script sees only the individual arguments; there will be no spaces. You can demonstrate that with:

printf "%s\n" "$@"

To preserve spaces, they must be quoted:

./programname  "hi    hello hi    usa  now  hello hello"

Better is to quote the arguments correctly:

./programname  hi "hello hi" usa now "hello hello"

thanks guys.. but I am writing this script so that end user can be as lazy as possible(since they are copying from somewhere and pasting it as arguments).

I thought maybe I can do it as put the whole argument as array.. and then after doing the replacing( " " to _ ) and then assign it back to $1,$2 .... ?

is this not possible in shell script?

so, my logic would be,

./scriptname whatever whatever1 whate ever2 whate ver 2006

so, script would see it as
@arrayname = $* # or possibly
value = $1,$2,$3,$4,$5,$6 <--i would insert extra just in case
and then possibly break it out using sed and awk.. but not sure how to assign it back...
newvalue =

No, it is not possible.

Each word on the command line is passed as a separate argument (to any program, not just shell scripts).

The only way to preserve whitespace is to quote it.

Try creating a script that does:

while read a
do
echo $a
#add parsing code here
done

Then run as:
script < data

The read function will read space delimited fields on the input line, and add the balance of the line to the last variable so:

read a b c d with input of a b c d e f
will return "d e f" for variable d