Reputation: 31
i have a file .dat with this format
#id|firstName|lastName|gender|birthday|creationDate|locationIP|browserUsed
933|Mahinda|Perera|male|1989-12-03|2010-03-17T13:32:10.447+0000|192.248.2.123|Firefox
1129|Carmen|Lepland|female|1984-02-18|2010-02-28T04:39:58.781+0000|81.25.252.111|Internet Explorer
and i want to replace a column (number of column is given from user with the command ./tool.sh -f <file> --edit <id> <column> <value>
) with the value (value is given from user with the same command) i cannot insert <column>
parameter inside awk
#!/bin/bash
if [ "$1"="-f" ] ; then
if [ "$3"="--edit" ] ; then
y=$6
x="$"$5
awk -F '|' ' '$4'==$1{$x-=$y;print }' <$2
fi
fi
i want something like this when user give this command
./file.sh -f file --edit 933 3 spyros
(the 3rd field than before has the value "Perera" change to "spyros)
933|Mahinda|spyros|male|1989-12-03|2010-03-17T13:32:10.447+0000|192.248.2.123|Firefox
Upvotes: 1
Views: 136
Reputation: 2362
As @ed-morton, but I've used named fields:
awk -v id=933 -v field=lastName -v value=spyros \
'BEGIN{OFS=FS="|"} NR==1 {for (i=1; i<=NF; i++) a[$i]=i; print} NR>1 {if($a["#id"]==id) $a[field]=value; print}' \
file
Upvotes: 0
Reputation: 203169
It looks like you want this:
awk -v key="$4" -v fldNr="$5" -v val="$6" 'BEGIN{FS=OFS="|"} $1==key{$fldNr=val;print}' "$2"
Upvotes: 2