0

I have a function

xyz()
{
x=$1*2
echo x
}

then I want to use it to replace a particular column in a csv file by awk.

File input.csv:

abc,2,something    
def,3,something1

I want output like:

abc,4,somthing    
def,6,something1

Command used:

cat input.csv|awk -F, -v v="'"`xyz "$2""'" 'BEGIN {FS=","; OFS=","} {$2=v1; print $0}'

Open file input.csv, calling function xyz by passing file 2nd filed as argument and result is stored back to position 2 of file, but is not working!

If I put constant in place of $2 while calling function it works:

Please help me to do this.

cat input.csv|awk -F, -v v="'"`xyz "14""'" 'BEGIN {FS=","; OFS=","} {$2=v1; print $0}'

This above line of code is working properly by calling the xyz function and putting the result back to 2nd column of file input.csv, but with only 14*2, as 14 is taken as constant.

1
  • 1
    do you know that can create functions in awk, or if you only need to multiply a column value by 2 you can say awk '{$2*=2;print}' file ? good luck. Commented Mar 29, 2014 at 13:04

1 Answer 1

2

There's a back-quote missing from your command line, and a UUOC (Useless Use of Cat), and a mismatch between variable v on the command line and v1 in the awk program:

cat input.csv|awk -F, -v v="'"`xyz "$2""'" 'BEGIN {FS=","; OFS=","} {$2=v1; print $0}'
                         ^ Here        ^ Here                            ^ Here

That should be written using $(…) instead:

awk -F, -v v="'$(xyz "$2")'" 'BEGIN {FS=","; OFS=","} {$2=v; print $0}' input.csv

This leaves you with a problem, though; the function xyz is invoked once by the shell before you start your awk script running, and is never invoked by awk. You simply can't do it that way. However, you can define your function in awk (and on the fly):

awk -F, 'BEGIN { FS = ","; OFS = "," }
         function xyz(a) { return a * 2 }
         { $2 = xyz($2); print $0 }' \
    input.csv

For your two-line input file, it produces your desired output.

Sign up to request clarification or add additional context in comments.

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.