Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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?

share|improve this question
3  
sed 's/ /---/g' Why would you need a separate utility? –  Mark Wagner Sep 15 '11 at 17:25
    
@embobo Post it as an answer and earn some free rep... –  voretaq7 Sep 15 '11 at 18:40

3 Answers 3

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 using sed and based on the example above would be major overkill.

share|improve this answer

awk version:

function join(a, start, end, sep, result, i) {
    sep = sep ? sep : " "
    start = start ? start : 1
    end = end ? end : sizeof(a)
    if (sep == SUBSEP) # magic value
       sep = ""
    result = a[start]
    for (i = start + 1; i <= end; i++)
        result = result sep a[i]
    return result
}

Call it with gawk with --source is your strings:

$ gawk -f join.awk --source 'BEGIN { split("foo bar quux",a); print join(a,1,3,"---") }'
foo---bar---quux

Shell script version:

function join() {
    for i in "$@"; do
        echo -n "$i""---"
    done
    echo
}

join foo bar baz quux 

Call it and trim the last separator:

$ ./join.sh | sed 's/\-\-\-$//'
foo---bar---baz---quux
share|improve this answer

Perl is not that complex for simple operations:

$ perl -e 's/ /---/g'
share|improve this answer
    
Considering OP wants to join parameters, that'd be perl -E 'say join(shift, @ARGV)' -- delim str1 str2 str3 ... The perl one-liner you've posted doesn't actually do anything (well, it changes $_, but that isn't passed into or out of the one liner). You probably wanted to pass -p as well. –  derobert Sep 15 '11 at 20:09

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.