Is there a portable unix shellscripting way of joining a number of strings together with a given separator, like so:
$ strjoin --- foo bar baz quux
foo---bar---baz---quux
Sure I could use a $scripting_language one liner or an ugly explicit loop in a shellscript function, but the unix hackers of old probably had some need for this as well, so someone has made a standard command like this that I don't know about somewhere in the past, right?
edit
The sed
method is certainly the easiest one in many situations, but it doesn't work if the strings can contain spaces. And many of the other answers also don't handle that. Are there any solutions other than the $IFS
trick that handle spaces (and all possible characters in general) and do not require writing a full loop?
For multi-character long separator, you can use:
sed
(as already pointed by @Mark)ex
printf
(but it will show the extra ending separator)using the following shell function (as per this SO post):
Usage:
For one-character long separators, you can use:
tr
Perl is not that complex for simple operations:
lam
Here is the example using
lam
command:paste
If the separator is one character long, then
paste
command can be used:In addition to @embobo's comment (which will hopefully make it into an answer soon),
perl
can be used to split and join arbitrary strings. This is more complex than usingsed
and based on the example above would be major overkill.awk
version:Call it with
gawk
with--source
is your strings:Shell script version:
Call it and trim the last separator:
The best method I've found is the ugly explicit loop you mentioned.
Usage:
Tested with Bash, Dash, and Zsh on Ubuntu, and should work in other Bourne-based shells.