Search code examples
linuxmove

Linux Move txt files not start with String to Another folder


The situation is
I have a directory A, I have a bunch of files and folders in the foldler. Such as folder B , foler C , tmp1.txt , Hello.txt , tmp3.txt , okay.txt.
And in folder B,there are also a bunch of files in it.
So I want to move all txt files recrusively to another folder such as /home.
Here is my code.

find . -name "*.txt"| grep -v [\s\S]*tmp[\s\S]* -exec mv {} /home \;

I can only select these files,however it won't execute move operation.

enter image description here

because linux find has path in result.So it annoy me a lot.


Solution

  • To move only regular files, add -type f and exclude the files you don't want with \!:

    find . -type f -name '*.txt' \! -name '*tmp*' -exec mv -i -t /home {} +
    

    The -i asks for permission to overwrite a file if it already exists and the + instead of the \; is used to move as many files as possible with one invocation of mv (and thus we need to specify the target directory with the -t option as {} contains more than one file).