Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

awk Joining n fields with delimiter

Tags:

awk

How can I use awk to join various fields, given that I don't know how many of them I have? For example, given the input string

aaa/bbb/ccc/ddd/eee

I use -F'/' as delimiter, do some manipulation on aaa, bbb, ccc, ddd, eee (altering, removing...) and I want to join it back to print something line

AAA/bbb/ddd/e

Thanks

like image 464
pistacchio Avatar asked Jan 24 '12 09:01

pistacchio


1 Answers

... given that I don't know how many of them I have?

Ah, but you do know how many you have. Or you will soon, if you keep reading :-)

Before giving you a record to process, awk will set the NF variable to the number of fields in that record, and you can use for loops to process them (comments aren't part of the script, I've just put them there to explain):

$ echo pax/is/a/love/god | awk -F/ '{
    gsub (/god/,"dog",$5);          # pax,is,a,love,dog
    $4 = "";                        # pax,is,a,,dog
    $6 = $5;                        # pax,is,a,,dog,dog
    $5 = "rabid";                   # pax,is,a,,rabid,dog

    printf $1;                      # output "pax"
    for (i = 2; i <= NF; i++) {     # output ".<field>"
        if ($i != "") {             # but only for non-blank fields (skip $4)
            printf "."$i;
        }
    }
    printf "\n";                    # finish line
}'
pax.is.a.rabid.dog

This shows manipulation of the values, as well as insertion and deletion.

like image 163
paxdiablo Avatar answered Oct 13 '22 10:10

paxdiablo