简体   繁体   中英

Adding comma between command line parameter

I want to call a procedure through unix script, it will be generic script so parameters can very. Calling statement will be some something like

<scriptname> <procedure name> <param1> <param2> <param3> <param4>.. so on

What I need is from 2nd command line paramater to last paramter I want all values comma separeted something like this

<param1>,<param2>,<param3>,<param4>

I can do this using a loop, that is from 2nd command line parameter I will itereate each parameter and add comma in it. My question is can I do this with single command?

Note :- Space should be handled properly if present is command line parameter, after last parameter there should not be any comma

All parameters is $@ . You can use sed to replace spaces with commas and then(or from the begining, cut the first field)

echo $@ |  sed s/" "/,/g | cut -d "," -f2-

a step forward, you can assign it to a variable:

comma_separated_params=`echo $@ |  sed s/" "/,/g | cut -d "," -f2-`

"${*:2}" expands to the list of arguments starting at $2, separated by the first character of IFS:

saveIFS=$IFS
IFS=","
args="${*:2}"
IFS=$saveIFS
echo "$args"

Note that this properly preserves spaces within arguments, rather than converting them to commas.

This technique below, performing the echo in a subshell, allows you to set IFS and then let the changes disappear with the subshell

$ set -- "a b c" "d e f" "g h i"
$ with_comma=$(IFS=,; echo "$*")
$ echo "$with_comma"
a b c,d e f,g h i

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM