JimS JimS - 1 month ago 6
Bash Question

process specific field given by the user bash

So the user gives me three inputs ID COLUMN VALUE. I want to replace the field in the line column with the value . I tried using awk like this

awk -F '|' -v COLUMN="$COLUMN" -v VALUE="$VALUE" '{if (FNR>1 && ID==$1) {$COLUMN=VALUE}}' $FILE


But I think I am doing something wrong with the syntax and I end up getting the whole file printed with no changes.

EXAMPLE:

#id|lastName|firstName|gender|birthday|creationDate|locationIP|browserUsed
7696581400586|Silva|Manuel|male|1987-08-31|2011-06-07T15:47:05.863+0000|193.126.75.5|Firefox
7696581400608|Li|Jun|female|1983-08-11|2011-05-11T05:20:42.017+0000|27.129.140.209|Chrome
7696581402447|Calvert|Charles|male|1985-09-18|2011-05-27T06:57:05.070+0000|41.51.52.232|Internet Explorer


Say the user gives me the inputs 7696581400608 2 Yung. So I replace the field 2 with the name Yung in the line that the id 7696581400608 is placed. So I replace Li with Yung.

Answer

You can use this awk:

awk -v id='7696581400608' -v col=2 -v val='Yung' 'BEGIN { FS=OFS="|" }
$1 == id { $col = val } 1' file.csv

#id|lastName|firstName|gender|birthday|creationDate|locationIP|browserUsed
7696581400586|Silva|Manuel|male|1987-08-31|2011-06-07T15:47:05.863+0000|193.126.75.5|Firefox
7696581400608|Yung|Jun|female|1983-08-11|2011-05-11T05:20:42.017+0000|27.129.140.209|Chrome
7696581402447|Calvert|Charles|male|1985-09-18|2011-05-27T06:57:05.070+0000|41.51.52.232|Internet Explorer
Comments