Sigularity
Sigularity

Reputation: 967

How to split - awk

I was wondering if I can make lists having left characters OR right characters after splitting with '=', and finally each character also get splitted with another '|' and ','. I have tried but failed because the number of lists are not fixed. Even C16 can be shown up, then it will be 16 item in the input.

Can you give me any hint?

Input

C1=34,C2=35,C3="99"

Output

C1|C2|C3#34,35,"99"

Upvotes: 1

Views: 57

Answers (3)

Claes Wikner
Claes Wikner

Reputation: 1517

 awk '{sub(/C1=34,C2=35,C3="99"/,"C1|C2|C3#34,35,\"99\"")}1' file 
    C1|C2|C3#34,35,"99"

Upvotes: 0

Ed Morton
Ed Morton

Reputation: 203502

awk -F'[=,]' '
{
    for (i=1;i<=NF;i+=2) {
        printf "%s%s", $i, (i<(NF-1)?"|":"#")
    }
    for (i=2;i<=NF;i+=2) {
        printf "%s%s", $i, (i<NF?",":ORS)
    }
}
' file
C1|C2|C3#34,35,"99"

Upvotes: 2

hek2mgl
hek2mgl

Reputation: 157967

You can pass multiple characters as the delimiter when using -F. The command could look like this:

awk -F'[,=]' '{printf "%s|%s|%s#%s,%s,%s", $1,$3,$5,$2,$4,$6}' input.txt

I'm using , and = as the delimiter. This makes it simple to access individual values and reassemble them using printf.

If the number of columns is unknown, you need to loop over the columns. First over the odd columns which are the names, then over the even columns which are the values. I suggest to put it into a script:

test.awk

BEGIN {
    FS="[,=]"
} 
{
    for(i=1;i<=NF;i+=2){
        if(i>=NF-1){
            fmt="%s"
        }else{
            fmt="%s|"
        }
        printf fmt,$i
    }   
    printf "#" 
    for(i=2;i<=NF;i+=2){
        if(i>=NF-1){
            fmt="%s"
        }else{
            fmt="%s,"
        }
        printf fmt,$i
    }   
}

Then execute it like this:

awk -f test.awk input.txt

Upvotes: 2

Related Questions