This is a follow up question from Copy data from each row in first column into a html hyperlink in the last column using Sed, Awk, etc
What i'm trying to do is replace the data in the first column and put it into the following hyperlink
This is an example of a file i get each day. Let's call this file input.csv and i want to transform it into output.csv
P.S. The number of rows varies each day.
INPUT.CSV
number|name|age|gender
B24|mike|22|male
B65|john|45|male
B74|jane|29|female
This is how i want it to look like:
OUTPUT.CSV
number|name|age|gender
<a href=https://www.abcdef.com/query=B24>B24</a>|mike|22|male
<a href=https://www.abcdef.com/query=B65>B65</a>|john|45|male
<a href=https://www.abcdef.com/query=B74>B74</a>|jane|29|female
i tried to continue from a previous solution that worked but this has the column at the end so i thought i could add a new awk statement to cut out the last column and replace with the first column but what i tried didn't work
'BEGIN{FS=OFS="|"} FNR==1{print $0,"link";next} {print $0,"<a href=https://www.abcdef.com/query="$1">"$1"</a>"}'
what i tried which didn't work:
'BEGIN{FS=OFS="|"} FNR==1{print $0,"slink";next} {print $0, "<a href=https://www.abcdef.com/query="$1">"$1"</a>"} {temp=$NF; $NF = ""; sub(",$", ""); print temp, $0}'
Appreciate the help!
CodePudding user response:
This sed
should work for you:
sed '1!s~[^|]*~<a href=https://www.abcdef.com/query=&>&</a>~' file
number|name|age|gender
<a href=https://www.abcdef.com/query=B24>B24</a>|mike|22|male
<a href=https://www.abcdef.com/query=B65>B65</a>|john|45|male
<a href=https://www.abcdef.com/query=B74>B74</a>|jane|29|female
Or this awk
:
awk 'NR > 1 {sub(/[^|] /, "<a href=https://www.abcdef.com/query=&>&</a>")} 1' file
number|name|age|gender
<a href=https://www.abcdef.com/query=B24>B24</a>|mike|22|male
<a href=https://www.abcdef.com/query=B65>B65</a>|john|45|male
<a href=https://www.abcdef.com/query=B74>B74</a>|jane|29|female
CodePudding user response:
Using sed
$ url=https://www.abcdef.com/search?query=
$ sed "1!s~^[^|]*~${url}&>&</a>~woutput.csv" input_file
$ cat output.csv
number|name|age|gender
<a href=https://www.abcdef.com/query=B24>B24</a>|mike|22|male
<a href=https://www.abcdef.com/query=B65>B65</a>|john|45|male
<a href=https://www.abcdef.com/query=B74>B74</a>|jane|29|female
CodePudding user response:
With your shown samples and efforts please try following awk
code. Using match
function here to get values from very first occurrence of |
in line to end of line and keeping rest of the functionality same for code.
awk -v firstHeader="<a href=https://www.abcdef.com/query=" -v secheader="</a>" '
BEGIN { FS=OFS="|" }
{
match($0,/\|.*/)
print $0, (FNR==1 ? "website" : firstHeader $1">"$1 secheader) substr($0,RSTART,RLENGTH)
}
' Input_file