zoe
zoe

Reputation: 311

set variable for number of lines in file

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

Answers (2)

PesaThe
PesaThe

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
  1. var=value is the correct syntax for variable assignment (no space before and after =)

  2. Don't use uppercase variables as they could clash with environmental or internal shell variables

  3. wc -l < file will not include the filename in the ouput

  4. awk -v var="$foo" assigns value of shell variable $foo to awk variable var
  5. $8==0 && $10==num if this condition is met, the default action, -- print $0 -- is executed

Upvotes: 2

sjsam
sjsam

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


  • The -n option with sed suppresses default printing of each lines.
  • The $ 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

Related Questions