1

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
3
  • 1
    It's very unclear what your awk script is supposed to do. You seem to be mixing up shell syntax with awk syntax and awk fields with shell positional parameters and/or variables. And idk why you have a -= in there at all given your description. Edit your question to provide a better explanation, an example of the operation you want to perform, and the expecte output given your posted sample input. Commented Mar 23, 2016 at 4:00
  • You should probably show us a sample invocation of your script. For example, you discuss ./tool.sh -f --edit, but that makes --edit into $2, yet you test for it in $3. It looks as if you redirect from $2, so presumably you mean ./tool.sh -f filename --edit …, but it isn't wholly clear what you expect in arguments 4, 5 and 6. You should probably use -v to convey values to awk from the shell. Commented Mar 23, 2016 at 4:03
  • i edit my question with the expected output Commented Mar 23, 2016 at 4:13

2 Answers 2

2

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"
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.