join() in AWK scripting language

AWK is small but very useful Unix scripting language that is mainly aimed at text files filtering and modification. If you're on embedded device you might expect bigger brothers (as Perl / Python) are not available, but AWK is usually shipped with busybox (= small).

One of missing functionalities is join() function (the opposite of splitting string by regular expression). One can implement it pretty easily, however:

function join(array, sep,
   result, i)
        if (sep == "")
                sep = " "
        else if (sep == SUBSEP) # magic value
                sep = ""
        result = array[1]
        for (i = 2; i in array; i++)
                result = result sep array[i]
        return result


split(s, arr, "|")
output = join(arr, "|")

As a result input string s will have the same contents as output. The function is useful for scripted modification of CSV files.

This entry was posted in en and tagged , , . Bookmark the permalink.