in this particular instance, i need to use set to set the variables. it looks as though the set command has issues accepting values between quotes as one single value.
sets $# to 1 and $1 to hello 'cat dog walk' money elephat .
The command:
echo $* | awk '{print $2}'
with its default field separator set to split fields on combinations of one or more spaces or tabs has field 1 set to hello , field 2 set to 'cat , field 3 set to dog , etc. and the awk command should print:
'cat
I have no idea how you got a leading " nor a trailing space from that command.
Without awk, the following shell commands might do what you want:
set hello 'cat dog walk' money elephat
printf "args=%d, arg1=%s, arg2=%s, arg3=%s, arg4=%s\n" $# "$1" "$2" "$3" "$4"
should print:
args=4, arg1=hello, arg2=cat dog walk, arg3=money, arg4=elephat
assuming that you're using a standards conforming shell such as bash or ksh.
@MadeinGermany: that will provide cat . To use awk ( instead of printf "%s\n" "$2" ) we need to get around the field splitting of awk with something like:
That is because in addition to your original problem specification you are using command substitution: $( ... ) which will cause the output of the command to be split into fields according to the IFS variable, which defaults to a space, a TAB and a newline. The same would go for variable expansion.
There is a difference between:
$ set -- hello 'cat dog walk' money elephant
$ echo "$2"
cat dog walk
and
$ var="hello 'cat dog walk' money elephant"
$ set -- $var
$ echo "$2"
'cat
in the first case there are 4 fields, and no field splitting is performed
in the second case there is field splitting after expansion of the variable "var", which results in 6 fields with the default IFS
--
You could try something like this:
$ oldIFS=$IFS
$ IFS="
"
$ set -- $(xargs -n1 < file)
$ IFS=$oldIFS
$ echo "$2"
cat dog walk
$