Akshay
Akshay

Reputation: 113

Split line with multiple delimiters in Unix

I have the below lines in a file

id=1234,name=abcd,age=76
id=4323,name=asdasd,age=43

except that the real file has many more tag=value fields on each line. I want the final output to be like

id,name,age
1234,abcd,76
4323,asdasd,43

I want all values before (left of) the = to come out as separated with a , as the first row and all values after the (right side) of the = to come below for in each line

Is there a way to do it with awk or sed? Please let me know if for loop is required for the same?

I am working on Solaris 10; the local sed is not GNU sed (so there is no -r option, nor -E).

Upvotes: 2

Views: 2448

Answers (4)

peak
peak

Reputation: 116650

The following simply combines the best of the sed-based answers so far, showing you can have your cake and eat it too. If your sed does not support the -r option, chances are that -E will do the trick; all else failing, one can replace R+ by RR* where R is [^,]

sed -r '1s/=[^,]+//g; s/[^,]+=//g'

(That is, the portable incantation would be:

sed "1s/=[^,][^,]*//g; s/[^,][^,]*=//g"

)

Upvotes: 0

Ed Morton
Ed Morton

Reputation: 203149

$ cat tst.awk
BEGIN { FS="[,=]"; OFS="," }
NR==1 {
    for (i=1;i<NF;i+=2) {
        printf "%s%s", $i, (i<(NF-1) ? OFS : ORS)
    }
}
{
    for (i=2;i<=NF;i+=2) {
        printf "%s%s", $i, (i<NF ? OFS : ORS)
    }
}

$ awk -f tst.awk file
id,name,age
1234,abcd,76
4323,asdasd,43

Assuming they don't really exist in your input, I removed the ...s etc. that were cluttering up your example before running the above. If that stuff really does exist in your input, clarify how you want the text "(n number of fields)" to be identified and removed (string match? position on line? something else?).

EDIT: since you like the brevity of the cat|head|sed; cat|sed approach posted in another answer, here's the equivalent in awk:

$ awk 'NR==1{h=$0;gsub(/=[^,]+/,"",h);print h} {gsub(/[^,]+=/,"")} 1' file
id,name,age
1234,abcd,76
4323,asdasd,43

Upvotes: 2

repzero
repzero

Reputation: 8412

sed -r '1 s/^/id,name,age\n/;s/id=|name=|age=//g' my_file

edit: or use

sed '1 s/^/id,name,age\n/;s/id=\|name=\|age=//g'

output

id,name,age
1234,abcd,76 ...(n number of fields)
4323,asdasd,43...

Upvotes: 0

Tomas M
Tomas M

Reputation: 7333

FILE=yourfile.txt

# first line (header)
cat "$FILE" | head -n 1 | sed -r "s/=[^,]+//g"

# other lines (data)
cat "$FILE" | sed -r "s/[^,]+=//g"

Upvotes: 0

Related Questions