awk

capture last line of file as integer variable and use in awk command


I am trying to capture the last line of a file as a variable for use in an awk command.

Here is an example of the file (the end of it) :

cat file.txt 
....
 phylum:Chlorophyta 1
 phylum:Mucoromycota 1
column 6:
 superkingdom:Eukaryota 99
column 7:
 
 99

I want to use that '99' as an integer in an awk command, saving it as a variable,

tail -n1 file.txt
99 

e.g.

div=$(tail -n1 file.txt)

echo $div
99

To be used in a 2nd file (conf.txt), to divide the numbers in the 2nd field:

cat conf.txt
Class 88
Family 78
Genus 44
Species 23

BUT, when I try to use the $div variable in the awk command (using -v flag as suggested here and elsewhere with awk when taking a variable) I get this error:

awk -v a=$div '{print $2/a}' conf.txt 
awk: can't open file {print $2/a}
 source line number 1


But when saivng 99 as a variable simply on the cmd line, It works just fine:

num=99
awk -v a=$num '{print $2/a}' conf.txt 
0.888889
0.787879
0.444444
0.232323

Are there extra spaces/characters in the capture from tail -1? I am missing something simple, but fundamental.

Ultimatey, I don't even want to have to save as a separate variable first If I dont have to, instead, just capture that last line number (99) and put directly into an awk cmd, e.g.:

awk  '{print $2/[tail -1 file.txt]}' conf.txt 

This is psuedo code (in the brackets) ...but, this would ultimately be what Id want...

Thanks for any help!


Solution

  • There's a space at the beginning of the last line, so the command is becoming

    awk -v a= 99 '{print $2/a}' conf.txt
    

    This is setting a to an empty string, treating 99 as the awk script, and the rest as filenames.

    Remove the spaces from $div.

    div=${div// /}