tamifo
tamifo

Reputation: 9

Directing output file name in a variable in awk

tmf@liphy$ cat data
5
3

tmf@liphy$ gawk -v "fileA"="testA" '$1<5{print $1 > "fileA"}' data

I want the output to go to testA. It goes to fileA instead. I tried various combinations of inverted commas. Nothing worked.

Upvotes: 1

Views: 229

Answers (3)

tamifo
tamifo

Reputation: 9

thank you for your comments. I tried many versions and it turned out that most quotes and the extra brackets can be deleted. The only important detail is not to put the quotes inside awk.

gawk -v "fileA"="testA" '$1<5{print $1 > (fileA)}' data

gawk -v fileA="testA" '$1<5{print $1 > (fileA)}' data

gawk -v fileA="testA" '$1<5{print $1 > fileA}' data

gawk -v fileA=testA '$1<5{print $1 > fileA}' data

fn="testA"; awk -v fileA="$fn" '$1<5 {print > fileA}' data

fn="testA"; awk -v fileA=$fn '$1<5 {print > fileA}' data

fn=testA; awk '$1<5' data > $fn

Upvotes: 0

dawg
dawg

Reputation: 103744

Given:

$ cat file
5
3

Have you considered you could use the shell rather than awk for creating the file:

 fn="testA"
 awk '$1<5' file > "$fn"

(Note that "$fn" is quoted in this case...)

But RavinderSingh13's method works too:

 awk -v fileA="$fn" '$1<5 {print > fileA}' file 

(Note that "$fn" is quoted since the shell is handling it but > fileA is not quoted since that is inside the awk script...)

Then, either case:

cat "$fn"   # "testA"
3

The takeaway is the variable expansions such as "$fn" need to be quoted in the shell but not inside of an awk script.

Upvotes: 1

RavinderSingh13
RavinderSingh13

Reputation: 133438

Could you please try following. You are using double quotes "fileA" which makes it string and will be considered as output file name as fileA(NOT as a variable fileA) where output should be written, rather than use variable name named fileA like > (fileA).

gawk -v "fileA"="testA" '$1<5{print $1 > (fileA)}' data

Upvotes: 2

Related Questions