How to count the number of lines in the file, then use the maths on this variable in bash?

advertisements

I am currently using a bash script to pipe a few other codes together but am new and have been stuck on this for the last day or so. Basically I need to count the number of lines within a file and then divide that by 4 to get the true number of objects in that file (each object takes up 4 lines).

For this I have looked around and ended up with the following code:

  a=$(wc -l "${o}"*)

  k=$(wc -l Unmatched_forward.fq)

  x=4

  #declare -i $a

  declare -i $k

  stats1_2=$((a / x))

  stats2_2=$((k / x))

  echo "${stats1_2} reads were joined."

  echo "${stats2_2} reads were not joined."

Within this code ${o} is the output from a previous file however needs to have ".fq" added to the end but whenever I try to add that to the end it comes up the error message below I have been trying to use the "*" to run on the file of which there are no other files similar.

"Unmatched_forward.fq" is another output file which I want to count the number of objects in.

I am using the declare option because I read that otherwise the number will be in string form instead of an integer and so maths cannot be done.

If anyone can help and explain whats wrong that would be great.

The error message is:

Overlay_code.sh: line 638: declare: `1265272': not a valid identifier
Overlay_code.sh: line 638: declare: `Unmatched_forward.fq': not a valid identifier
Overlay_code.sh: line 643: 1265272 Unmatched_forward.fq: syntax error: invalid arithmetic operator (error token is ".fq")

Whats more confusing is I am suddenly getting the '1265272' number appearing and have no idea why!


You should check that your invocation of wc truly returns only an integer, because I think it is not. Probably the following happens

$>  wc -l Unmatched_forward.fq
128 Unmatched_forward.fq

So it returns the line count and the filename. The following should work

k=$(wc -l Unmatched_forward.fq | awk '{print $1}')
x=4
stats1_2=$((k / x))

Note that bash's (()) only supports integer math, so all results will get rounded. If you need floating point precision, check out bc