-1

I'm having issue to use a variable inside cat command inside a .sh, it's not using it and I don't understand why !

I want to count lignes inside multiple file with the same name exept for the date for the sevens past days:

something_exemple_20211015_somethingelse.txt something_exemple_20211014_somethingelse.txt ...

I wrote this :

#!/bin/bash

for i in {1..7}; do
    #Get the date of the seven days before inside dday var
    dday=date +%Y%m%d -d ''"$i"' days ago'
    number_ligne=0
    #Count the number of line
    number_ligne=cat /home/me/*exemple_*$dday* | wc -l
    echo $dday
    echo $number_ligne
done

The output looks like it's now using dday and doing this :

cat /home/me/*exemple_**

Do you have any idea

Thanks you !

Neakath
  • 1
  • 1

2 Answers2

0

To capture the output of a command, you need Command Substitution:

number_ligne=$(cat /home/me/*exemple_*$dday* | wc -l)
#            ~~                                     ~
choroba
  • 216,930
  • 22
  • 195
  • 267
  • You might want to add the other line, too: `dday=date ...` -> `dday=$(date ...)` – Maxxim Oct 15 '21 at 15:47
  • `number_ligne="$(wc -l /home/me/*exemple_*"$dday"*)"` (Or, if it is somehow guaranteed to match one file, then `number_ligne="$(wc -l < /home/me/*exemple_*"$dday"*)"` prevents `wc` from printing out the file name.) – Andrej Podzimek Oct 15 '21 at 15:49
  • @AndrejPodzimek: this should only be a side-note IMO, as using `cat` may be unnecessary, but it's not wrong – Maxxim Oct 15 '21 at 15:53
  • @Maxxim That depends on the definition of *wrong*… The side note is that a useless extra process is tremendously expensive, especially when something like that occurs in a loop. The main problem is that without `set -o pipefail` (or an explicit inspection of `${PIPESTATUS[@]}`), useless pipelines (starting with `cat`) can hide file access errors: `cat nonexistent | wc -l` returns a zero status (success), whereas `wc -l nonexistent` and `wc -l < nonexistent` both return errors, as they should. – Andrej Podzimek Oct 15 '21 at 16:03
  • @AndrejPodzimek: *wrong* in the sense of *won't work*. The OP appears to be a beginner. You're talking about optimization and things outside the scope of the original code, which is more suited for advanced users. – Maxxim Oct 15 '21 at 16:12
0

Also, don't overdo the quotes and make then unnecessarily confusing, and avoid that UUoC.

for i in {1..7}; do
  dday=$( date +%Y%m%d -d "$i days ago" )
  number_ligne=$( wc -l < /home/me/*exemple_*$dday* )
  echo "$dday: $number_ligne"
done
Paul Hodges
  • 10,927
  • 1
  • 16
  • 30