user3475535
user3475535

Reputation: 1

awk syntax to invoke function with argument read from a file

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.

Upvotes: 0

Views: 53

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 754670

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.

Upvotes: 2

Related Questions