1

I'm writing a script to create a directory named with today's date (yyyy_mm_dd), and then move all files ending in today's date to that directory. Is there a better way to move the files to the directory, as what I've done selects the directory as well.

now=$(date '+%Y_%m_%d')
mkdir $now
mv *$now $now/
3
mv *?"$now" "$now/."

will ensure that your just-created directory is not selected for move, by requiring there to be at least one character (?) in front of the timestamp.

1

The find command can filter on file types as well as file names.
So I think this will do what you want:

now=$(date '+%Y_%m_%d')
find . -name "*$now" -type f -print0 | xargs -0 mv -t $now/

though you may need to think about whether there are any oddities in your filenames (such as other directories containing the date string) before running this on a large batch.

2
  • What if there's a directory called foo$now? Why do you assume that shouldn't be moved? – terdon Apr 7 '17 at 14:08
  • @ terdon Because the question asks how to move files and not the directory in question. On a natural reading, that means the intention is to exclude all directories, though I can see how you might read it differently. – SauceCode Apr 7 '17 at 14:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.