8

I have a set of files created from Monday to Friday:

a -- > 08/20
a1---> 08/21
a2---> 08/21
a3---> 08/21
a4---> 08/22
a5 --> 08/23

I need to move only the 08/21 files to a different folder.

How can I do this?

Matthias Braun
  • 7,797
  • 7
  • 45
  • 54
user43067
  • 307
  • 2
  • 4
  • 6
  • I don't know why this was closed, because the "duplicate" has nothing to do with moving the files to directories. Nevertheless, this is my answer: `find *.* -type f -exec bash -c 'mv "$@" $(date --date=@$(stat -c %Y "$@") +%Y-%m)/"$@"' _ {} \;` it moves all files in followingly e.g. `zoo.txt` goes to `2020-01/zoo.txt` etc. – Ciantic Aug 21 '21 at 17:56

3 Answers3

17

Let's assume that modification times of the files are kept (files are not modified after they were created). Then, you can play with find command and -mtime option which searches for files whose data was last modified X days ago. So to find all files created e.g. 48 hours ago in the current working directory use

find ./ -type f -mtime 2

to move them to other directory

find ./ -type f -mtime 2 -exec mv {} DEST_DIR/ \;

Additionally, you can try to estimate the number of days from the current date and the date from which you requested the files (in this example 22)

DAY_CUR="`date +%d`"
DAY_REQ=22
DAY_DIF=$((DAY_CUR - DAY_REQ))
    
find ./ -type f -mtime $DAY_DIF -exec mv {} DEST_DIR/ \;

The code is not perfect as it doesn't handle situations where the two days are from two different months but it illustrates how you can proceed.

CervEd
  • 156
  • 7
dsmsk80
  • 3,038
  • 1
  • 15
  • 20
7

So you want to move files based on their attributes. This means you have to identify or "find" the files and then move the result to a different folder.

The find utility will do an excellent job :-)

find called without any arguments will just list the complete folder content. You can then specifiy various filter criteria. For a complete list see man find (http://unixhelp.ed.ac.uk/CGI/man-cgi?find).

Here are some examples:

  [..]
   -mmin n
      File's data was last modified n minutes ago.

   -mtime n
      File's  data was last modified n*24 hours ago.  See the comments
      for -atime to understand how rounding affects the interpretation
      of file modification times.

   -newer file
      File was modified more recently than file.  If file  is  a  sym-
      bolic  link and the -H option or the -L option is in effect, the
      modification time of the file it points to is always used.
  [..]

You can then use -exec to call mv and use {} as a placeholder for the current file.

Example: find /some/path/ -mtime +4 -exec mv {} /some/other/path/

Pro-Tip: Call find without -exec to see if you get the right files :-)

echox
  • 17,753
  • 7
  • 51
  • 56
1

You can use the find command to determine the files created on a day and use a filename pattern to further constrict the search. Use the -exec in find to mv the files.

unxnut
  • 5,908
  • 2
  • 19
  • 27