I have files with random numbers in /home/user/files folder (every 4 days I have new ones). for example:


I want to take only last modified files (the newest) and copy them to different location (/home/user/fixed) without that numbers in file name.

I know how to filter and copy that using find command but I don't know how copy all of them without that numbers.

find $files_are_here -maxdepth 1 -mtime -2 -type f -exec cp {} $new_path \;

This will copy all of the files modified in the last 2 days to the new path but with original name. In my case:


but I would like to have only john, tom and simon inside that folder. So after I run my script again they will be replaced by the newest one.


The following is hopefully self explainatory

find -maxdepth 1 -mtime -2 -type f  -exec bash -c 'name=${1##*/}; cp  "$name" /some/other/dir/${name%%[0-9]*}' _ {} \;
|improve this answer|||||
  • This assumes that you have cd’ed into the directory where the existing files are, and it breaks if you take out the -maxdepth 1. You can fix both of these by changing cp "$name" … to cp "$1" … – G-Man Says 'Reinstate Monica' Aug 26 '14 at 19:34
  • P.S. The word is “explanatory”. – G-Man Says 'Reinstate Monica' Aug 26 '14 at 19:34
  • @G-Man it indeed is 'explanatory'. I stand corrected. find when no path specified, assumes the $(PWD). So since I was not sure where OP's files were located I assumed the current dir. Then of course the command changes slightly. names${1##*/} would no longer be necessary. Just a way to show how PE (Parameter Expansion) works – Valentin Bajrami Aug 26 '14 at 20:19
  • Yes, I know find defaults to a path of .. But we do know where the OP’s files are located – they’re in $files_are_here. … … … … I don’t understand what you mean by “names=${1##*/} would no longer be necessary” – you still need it to have a basename to strip the digits from, in ${name%%[0-9]*}. – G-Man Says 'Reinstate Monica' Aug 26 '14 at 20:32
  • If we used "$1" as you suggested, then we could use "${1%%[0-9]*}" as being the positional parameter without defining a variable. – Valentin Bajrami Aug 26 '14 at 20:44
find -mtime -2 \
     -maxdepth 1 \
    \! -type d \
    \( -name 'simon*' \
    -o -name 'tom*' \
    -o -name 'john*' \
    \) | tar -T - \
     --xform='s/[0-9]*$//' \
     -cf - | tar -C ./path/to/destination --keep-newer-files -xf -

I think that will do it - it appears to work for me. So long as the simon, tom, and john files are intended to be overwritten once every two days - I believe this should do it. Either that or it is very close. Oh, but, it does require GNU tar - and probably GNU find as well, though I'm not sure about the latter. I didn't check too hard on those because the majority of those were your own options.

|improve this answer|||||

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.