gawk: Join Function
1
1 10.2.6 Merging an Array into a String
1 -------------------------------------
1
1 When doing string processing, it is often useful to be able to join all
1 the strings in an array into one long string. The following function,
1 'join()', accomplishes this task. It is used later in several of the
1 application programs (⇒Sample Programs).
1
1 Good function design is important; this function needs to be general,
1 but it should also have a reasonable default behavior. It is called
1 with an array as well as the beginning and ending indices of the
1 elements in the array to be merged. This assumes that the array indices
1 are numeric--a reasonable assumption, as the array was likely created
1 with 'split()' (⇒String Functions):
1
1 # join.awk --- join an array into a string
1
1 function join(array, start, end, sep, result, i)
1 {
1 if (sep == "")
1 sep = " "
1 else if (sep == SUBSEP) # magic value
1 sep = ""
1 result = array[start]
1 for (i = start + 1; i <= end; i++)
1 result = result sep array[i]
1 return result
1 }
1
1 An optional additional argument is the separator to use when joining
1 the strings back together. If the caller supplies a nonempty value,
1 'join()' uses it; if it is not supplied, it has a null value. In this
1 case, 'join()' uses a single space as a default separator for the
1 strings. If the value is equal to 'SUBSEP', then 'join()' joins the
1 strings with no separator between them. 'SUBSEP' serves as a "magic"
1 value to indicate that there should be no separation between the
1 component strings.(1)
1
1 ---------- Footnotes ----------
1
1 (1) It would be nice if 'awk' had an assignment operator for
1 concatenation. The lack of an explicit operator for concatenation makes
1 string operations more difficult than they really need to be.
1