awk opposite of split

Here's a solution that doesn't rely on gawk or knowing the length of the array and lets you put a separator (space in this case) string between each array element if you like:

color = "#FFFF00"
printf "color original: %s\n", color
split(color, chars, "")
joined = sep = ""
for (i=1; i in chars; i++) {
    joined = joined sep chars[i]
    sep = " "     # populate sep here with whatever string you want between elements
}
printf "color joined: %s\n", joined

I also cleaned up the incorrect use of printf and the spurious semi-colons.

In the above script split(color, chars, "") relies on having a version of awk that will split a string into an array given a null field separator, which is undefined behavior per POSIX, but that's not what this answer is about - the question is how to join array elements not how to split them.


Here is a way with POSIX Awk:

br = "red,orange,yellow,green,blue"
ch = split(br, de, ",")
print "original: " br
printf "joined: "
for (ec in de) printf ec == ch ? de[ec] "\n" : de[ec] "-"

Output:

original: red,orange,yellow,green,blue
joined: red-orange-yellow-green-blue

Tags:

Awk