简体   繁体   中英

Shell Script split concatenate and re-use

In Shell script I want to achieve something like below:

str="india,uk,us,uae"

I want to split it and concatenate each item as below and assign to some variable

newstr = '-myParam="india" -myParam="uk" -myParam="us" -myParam="uae"'

so that I can use above concatenated string in my next command as below

curl "admin/admin" "localhost" $newstr.

I found a way using local IFS and for loop but the variable updated inside loop is not retaining value outside of loop because it runs in a separate bash.

Read the params into an array:

IFS=, read -a params <<< "$str"

And then loop through them and store the command in an array:

for i in "${params[@]}"; do
   command+=(-myparam=\"$i\")
done

Now you can expand it using printf "${command[@]}" :

$ printf "%s " "${command[@]}"
-myparam="india" -myparam="uk" -myparam="us" -myparam="uae"

That is, now you have to say:

curl "admin/admin" "localhost" "${command[@]}"

This is based on this answer by chepner: command line arguments fed from an array .

str="india,uk,us,uae"
var=-myparam=\"${str//,/\" -myparam=\"}\"
echo $var

Below code would do :

$ str="india,uk,us,uae"
$ newstr=$(awk 'BEGIN{RS=","}{printf "-myParam=\"%s\" ",$1}' <<<"$str")
$ echo "$newstr"
-myParam="india" -myParam="uk" -myParam="us" -myParam="uae" 

Also when you pass new string as parameter to curl, double quote it to prevent word splitting and globbing, so do :

curl "admin/admin" "localhost" "$newstr"

Note: <<< or herestring is only supported in a few shells (Bash, ksh, or zsh) if I recall correctly. If your shell does not support it use echo,pipe combination.

IFS=',' read -ra a <<< "${str//,/\",}";
curl "admin/admin" "localhost" "${a[@]/#/ -myParam=\"}\""

Explanation:

Starting with:

str="india,uk,us,uae";

Next, split the string into an array, using parameter substitution to insert " before each comma:

IFS=',' read -ra a <<< "${str//,/\",}";

Finally, we can get newstr through parameter substitution (while also appending the final " ):

newstr="${a[@]/#/ -myParam=\"}\"";

newstr is now set to '-myParam="india" -myParam="uk" -myParam="us" -myParam="uae"' . We can skip the previous step and go straight to:

curl "admin/admin" "localhost" "${a[@]/#/ -myParam=\"}\""

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