Reputation: 311
I am trying to extract the number of lines in a file to a variable and then use this variable in the same script but it isn't working for me (the resulting file is empty but the code works if I hard code the number instead of the variable) I have the following code:
#!/bin/bash
set -e
set -u
mydir=`pwd`
echo $mydir
sample_info= sample.txt
NUMOFSAMPLES=$(wc -l $sample_info)
echo $NUMOFSAMPLES
## now apply my filter
awk '{if($8==0 && $10 == $NUMOFSAMPLES)print$0}' SJ.all > SJ.all.samples
Please help!
Upvotes: 0
Views: 360
Reputation: 7499
sample_info="sample.txt"
num_of_samples=$(wc -l < "$sample_info")
awk -v num="$num_of_samples" '$8==0 && $10==num' SJ.all > SJ.all.samples
var=value
is the correct syntax for variable assignment (no space before and after =
)
Don't use uppercase variables as they could clash with environmental or internal shell variables
wc -l < file
will not include the filename in the ouput
awk -v var="$foo"
assigns value of shell variable $foo
to awk
variable var
$8==0 && $10==num
if this condition is met, the default action, -- print $0
-- is executedUpvotes: 2
Reputation: 21955
I would suggest a different approach using sed
sample_info=sample.txt
NumOfSamples=$(sed -n '$=' <"$sample_info")
# Note you shouldn't use full upper-case identifiers for user variables.
What happens here
-n
option with sed
suppresses default printing of each lines.$
looks for the last line in file and =
prints the line number. Finally with awk, you can be more idiomatic
awk -v n=$NumOfSamples '$8==0 && $10==n' SJ.all >SJ.all.samples
Upvotes: 1