Scott
Scott

Reputation: 6736

bash: display only files that contain a date in their file name

I am trying to figure out the best method to accomplishing this task, where I have a directory that has multiple files with varying file name formats, and I need to parse out those files that have a date in the file name (format of %F, or YYYY-MM-DD) from those that don't, then iterate through each of them using a mix of a for loop and a case loop to segregate between files that have a date in the file name and those that don't. Pseudo code is as follow:

#!/bin/bash
files=`ls`
for file in $files; do
  # Command to determine whether $file has a date string
  case (does variable have a date string?) in
    has)   # do something ;;
    hasnt) # do something else ;;
  esac
done

What is the best command to plug in for the comment, and then easiest way to execute such a case statement based off the command?

Upvotes: 1

Views: 4355

Answers (2)

shellter
shellter

Reputation: 37258

Given your original code, you can do

files=`ls`
for file in $files; do
  # Command to determine whether $file has a date string
  case ${file} in
    *2[0-9][0-9][0-9]-[0-1][0-9]-[0-3][0-9]* )   
       # note that this date-only matching reg-exp is imperfect
       # it will match non-dates like 2011-19-39
       # but for cases where date is generated with date %F 
       # it will work OK
       : # do something 
    ;;
    * ) # do something else ;;
  esac
done

Or as @matchw recommends, you can use that pattern in a find

find . -type f -name '*2[0-9][0-9][0-9]-[0-1][0-9]-[0-3]-[0-9]*' -print0 \
  | xargs yourCommand

I hope this helps.

P.S. as you appear to be a new user, if you get an answer that helps you please remember to mark it as accepted, and/or give it a + (or -) as a useful answer.

Upvotes: 5

George Kastrinis
George Kastrinis

Reputation: 5172

Use grep with a regular expression

Something like

grep -E "20[0-9]{2}\-(0[1-9]|1[0-2])\-([0-2][0-9]|3[0-1])"

eg.

echo "FOO_2011-05-12" | grep -E "20[0-9]{2}\-(0[1-9]|1[0-2])\-([0-2][0-9]|3[0-1])"

Upvotes: 2

Related Questions