Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash separate parameters with specific delimiter

I am searching for a command, that separates all given parameters with a specific delimiter, and outputs them quoted.

Example (delimiter is set to be a colon :):

somecommand "this is" "a" test

should output

"this is":"a":"test"

I'm aware that the shell interprets the "" quotes before passing the parameters to the command. So what the command should actually do is to print out every given parameter in quotes and separate all these with a colon.

I'm also not seeking for a bash-only solution, but for the most elegant solution.
It is very easy to just loop over an array of these elements and do that, but the problem is that I have to use this inside a gnu makefile which only allows single line shell commands and uses sh instead of bash.

So the simpler the better.

like image 471
bricklore Avatar asked Apr 17 '26 15:04

bricklore


1 Answers

How about

somecommand () {
    printf '"%s"\n' "$@" | paste -s -d :
}

Use printf to add the quotes and print every entry on a separate line, then use paste with the -s ("serial") option and a colon as the delimiter.

Can be called like this:

$ somecommand "this is" "a" test
"this is":"a":"test"
like image 70
Benjamin W. Avatar answered Apr 19 '26 09:04

Benjamin W.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!