简体   繁体   中英

Awk shell scripting

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

看起来您想要这样:

awk -v key="$4" -v fldNr="$5" -v val="$6" 'BEGIN{FS=OFS="|"} $1==key{$fldNr=val;print}' "$2"

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM