-1

I have a need in a bash script to see if a string ends in an underscore and a date, of the form:

   _yyyymmdd

I don't care about validating the date at this point, just that I have something like

 abc_def_yyyymmdd

or

 abc_yyyymmdd

(Note there may be other underscores in the name that I don't care about; I only care that it ends in _yyyymmdd -- an underscore followed by 8 digits).

Can you assist me in that pattern match test? Let me be clear based on a comment that I don't care about validating the date at this point, just that the string (a filename) ends in an underscore and 8 digits.

Ray
  • 5,885
  • 16
  • 61
  • 97

2 Answers2

4

You may use the below regex,

[[ $str =~ _[0-9]{8}$ ]]

[0-9]{8} would match exactly 8 digit charcaters. $ asserts that we are at the end.

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
2

You don't need regex.

case $filename in
  *_[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9] )
    echo "fine";;
  *)
    echo "fail";;
esac
tripleee
  • 175,061
  • 34
  • 275
  • 318
  • Thanks. What do you see as an advantage to no-regex vs. using regex? – Ray Aug 20 '15 at 17:55
  • Globs are simpler, computationally less expensive, and often (though not in this case) easier to read and debug. Additionally, this `case` construct is portable all the way back to Unix v7 and the original Bourne shell. – tripleee Aug 20 '15 at 17:59
  • It's a lot more concise, though, when it's available. If POSIX compatibility is needed, you can use `expr "$filename" : '.*_[0-9]\{8\}$'` (at the expense of starting a new process, of course.) – chepner Aug 20 '15 at 18:04