Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending a string to all elements of cells in a column using awk or bash

Tags:

bash

awk

I have the following text file:

$ cat file.txt
# file;GYPA;Boston
Josh      81-62    20
Mike      72-27    1;42;53
Allie     71-27    24;12

I would like to add GYPA to every element of the third column in the following manner:

GYPA:20
GYPA:1;GYPA:42;GYPA:53
GYPA:24;GYPA:12

so far, I have

cat combine.awk

NR==1 {
    FS=";"; Add=$2
}

{
    FS="\t"; split($3,a,";");
    for (i in a) {
        print Add":"a[i] 
    }

}

the array part did not work.

like image 395
Shahin Avatar asked Jun 05 '26 17:06

Shahin


2 Answers

Assuming there's no backreference (e.g. &) or escape chars in the prefix string you want to add:

$ awk -F';' 'NR==1{add=$2":"; FS=" "; next} {gsub(/(^|;)/,"&"add,$3); print $3}' file
GYPA:20
GYPA:1;GYPA:42;GYPA:53
GYPA:24;GYPA:12
like image 64
Ed Morton Avatar answered Jun 08 '26 08:06

Ed Morton


You could do it like this:

#!/usr/bin/awk -f
NR == 1 {
    # Get the replacement string from the first line
    split($0, h, ";");
    add = h[2]
    next
}
{
    # split the last field by ';' into the array 'a'
    # n contains the number of elements in 'a'
    n=split($3,a,";");
    for(i=1;i<=n;i++){
        # print every element of a, separate by ','
        printf "%s%s:%s", (i-1)?",":"", add, a[i];
    }
    # finish the line by printing the ORS
    print ""
}
like image 29
hek2mgl Avatar answered Jun 08 '26 09:06

hek2mgl