awk print redirection to variable file name

Hello,

i need to redirect the output of print to a variable file name:

#This is normal
awk '{ print $17 > "output.txt" }' input

#I need something like this
awk '{ print $17 > "output_${25}.txt" }' input

how to format the output file name to contain a variable?

can you try this:

awk -v value=$variable '{ print $17 > "output_value.txt" }' input

Hi Nazeeb, :slight_smile:

check the below code

awk '{ print $17 > "output_"$25".txt" }' input

Thanks krao!!!

awk -F, '{ print $1 > "output_"$2".txt"}' 1 

works fine!

But

nawk -FS=, '{ print $1 > "output_"$2".txt"}' 1

generates error :confused:

i think I'll manage it :slight_smile:

hi nazeeb,

can u provide a sample input , in that plz specify what delimiters you are using like , = : ... etc. so that i will try to help you in nawk code

Hi krao,

really appreciate your conecern.

the input is just a test file to get the output working on a trial and error basis:

filename: 1
content:

i tried so many things (some of which looked funny too):

nawk -FS=, '{ print $1 > "output_'$2'.txt"}' 1
nawk -FS=, '{ print $1 > "output_\"$2\".txt"}' 1

but it produces output file name with "$" in it.

On the contrary, awk produces the following files:
output_2.txt
output_5.txt
output_8.txt

I think I need a way around to what i am trying to achieve.

This works as long as the variable containing the filename is a positional variable. But if you are using some logic to change the file names not once per line but on some other key, I could find no way to output to a filename in a named variable. So I had to use awk to make a shell script with

cat >filename <<EOF
....
EOF

and then execute that.