Warm tip: This article is reproduced from stackoverflow.com, please click
awk bash

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

发布于 2020-04-07 23:22:06

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.

Questioner
user171558
Viewed
44
Ed Morton 2020-02-01 06:38

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