awk opposite of split

后端 未结 5 870
执笔经年
执笔经年 2021-01-12 04:03

what would be an opposite of split() in awk? Imagine I have array containig characters/integers.

What I\'ve tried:

color =          


        
相关标签:
5条回答
  • 2021-01-12 04:44

    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
    
    0 讨论(0)
  • 2021-01-12 05:01

    Knowing that the opposite of split() is join(), a mere Google Search gives me this page, which seems to contain the solution : http://www.gnu.org/software/gawk/manual/html_node/Join-Function.html . It joins all the elements of an array together, and returns the corresponding string.

    ['f','o','o'] => "foo"
    

    Have fun

    0 讨论(0)
  • 2021-01-12 05:03

    What you want (in your loop) is string concatenation.

    0 讨论(0)
  • 2021-01-12 05:08

    Using GNU awk 4.1

    #!/usr/bin/awk -f
    @include "join"
    BEGIN {
       split("#FFFF00", a, "")
       print join(a, 1, length(a), SUBSEP)
    }
    

    https://stackoverflow.com/questions/16529716#16529730

    0 讨论(0)
  • 2021-01-12 05:09

    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.

    0 讨论(0)
提交回复
热议问题