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.
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
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 ""
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With