Problem with awk instructions and bash variable

Hi everyone,

I'm trying to write a small script to automatize row data treatment. However, I got some trouble with the awk command.

I want to use awk to extract a define paragraph from a text file. The first and final lines are defined externally in two variables called debut and fin.

I first tried :

awk 'FNR>=$debut && FNR<=$fin' 2d_Pt_110 >> $i.$exp

But it doesn't work... I found that the variable cannot be simply called with $ in the awk instruction. So I tried the following command instead :

awk deb="$debut" fif="$fin" 'FNR>=deb && FNR<=fif' 2d_Pt_110 >> $i.$exp

But it's not working as well. I got the following error :

awk: can't open file FNR>=deb && FNR<=fif
 source line number 1

Do you have an idea to fix my problem ?

Thank you,
Best.

You were very close!

# Modern way, variables get set before any BEGIN block, etc
awk -v deb="$debut" -v fif="$fin" 'FNR>=deb && FNR<=fif' 2d_Pt_110 >> $i.$exp

Or alternately

# Old-fashioned way, variables not set before any BEGIN block but before the file
awk 'FNR>=deb && FNR<=fif' deb="$debut" fif="$fin" 2d_Pt_110 >> $i.$exp
1 Like

Thank you ! :slight_smile: It's helping me a lot !

1 Like