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
"&"
now that was a nugget I didn't knowawk
could behave likesed
with... Thank you.Can you please explain what are the
"
s around the&
for? My understanding is that&
is either the empty string (when^
matches the beginning of$3
) or;
;add
is the second header followed by:
. But why those two"
s?The 2nd argument to
gsub()
is a string."&"and
is the string you get when you concatenate the string"&"
with the value of the variableand
. The"
s are just string delimiters -&
alone would be an awk language symbol while"&"
is a string containing the character&
which means a backreference for the entire matching string from the 1st arg in the context of the 2nd arg to gsub().In every way,
&
is not an awk variable - on it's own as&
it's a symbol and within"&"
its a character in a string. Yes,add
is an awk variable.Not sure what you're trying to do there.
^.
meansany character at the start of a string
- it seems unlikely you want to replace that with anything. Please ask a new question with it's own sample input/output if you'd like help.