Shell variable expansion in awk

I want to split one file input.tab into two separate ones, odd lines to input_reads1.txt , even lines to input_reads2.txt for a serial of files with similar name pattern. Also I want to "match" input/output file names to keep consistency of file name:

CSEL_02.0_input.tab 
CSEL_03.4_input.tab
CSEL_04.9_input.tab
CSEL_05.6_input.tab
CSEL_06.6_input.tab
CSEL_11.0_input.tab
CSEL_18.0_input.tab
......

One example:
CSEL_02.0_input.tab

seq1_description CAATCGATCGACTAG
seq2_description GTCGATCGACTAGGA
seq3_description CTCGATCGACTAGCT
seq4_description CGATCGCGCGGGGAA

Outputs file names and contents are:
CSEL_02.0_reads_R1.txt

seq1_description 
CAATCGATCGACTAG
seq3_description 
CTCGATCGACTAGCT

CSEL_02.0_reads_R2.txt

seq2_description 
GTCGATCGACTAGGA
seq4_description 
CGATCGCGCGGGGAA

I have tried:

for i in 02.0 03.4 04.9 05.6 06.6 11.0 18.0; do 
awk -v stem=CSEL_${i}_reads_R '{print $1"\n"$2 >> "stem"(NR%2?1:2)".txt"}' CSEL_${i}_input.tab
done 

But I got:

stem1.txt
stem2.txt

Shell variable "stem" did not expand as I want to match input/output file names.
What did I miss?

It didn't expand because you gave awk the quoted string literal "stem" , not the unquoted variable name stem .

awk sets FILENAME for your convenience, however, might be easier to use that.

Also, > is a little different in awk in that it keeps the file open. The only difference between > and >> is that the very first write of > will truncate the file, but >> never truncates at all.

awk 'FNR==1 { F=FILENAME ; sub(/_input[.]tab/, "", F); } { print $1"\n"$2 > F "_reads_R" (NR%2)+1 }' inputfile
1 Like

quoted string literal "stem"
Ahh, it's not so simple until you pointed out.
Thanks for pointing out the difference between ">" and ">>", using ">>" is easy to cause trouble when the script is re-run unless the file is deleted each time before start.
Also I like the FILENAME version. The print part should be:

{ print $1"\n"$2 > F "_reads_R" (NR%2)+1 ".txt"}

according to file name requirement in the example, right? Thanks a lot!