I want to copy recursively files to its parent folder for a specific file extension. For example:
./folderA/folder1/*.txt to ./folderA/*.txt
./folderB/folder2/*.txt to ./folderB/*.txt
etc.
I checked cp
and find
commands but couldn't get it working.
I suspect that while you say copy, you actually mean to move the files up to their respective parent directories. It can be done easily using find
:
$ find . -name '*.txt' -type f -execdir mv -n '{}' ../ \;
The above command recurses into the current directory .
and then applies the following cascade of conditionals to each item found:
-name '*.txt'
will filter out only files that have the .txt
extension-type f
will filter out only regular files (eg, not directories that – for whatever reason – happen to have a name ending in .txt
)-execdir mv -n '{}' ../ \;
executes the command mv -n '{}' ../
in the containing directory where the {}
is a placeholder for the matched file's name and the single quotes are needed to stop the shell from interpreting the curly braces. The ;
terminates the command and again has to be escaped from the shell interpreting it.I have passed the -n
flag to the mv
program to avoid accidentally overwriting an existing file.
The above command will transform the following file system tree
dir1/
dir11/
file3.txt
file4.txt
dir12/
file2.txt
dir2/
dir21/
file6.dat
dir22/
dir221/
dir221/file8.txt
file7.txt
file5.txt
dir3/
file9.dat
file1.txt
into this one:
dir1/
dir11/
dir12/
file3.txt
file4.txt
dir2/
dir21/
file6.dat
dir22/
dir221/
file8.txt
file7.txt
dir3/
file9.dat
file2.txt
file5.txt
To get rid of the empty directories, run
$ find . -type d -empty -delete
Again, this command will traverse the current directory .
and then apply the following:
-type d
this time filters out only directories-empty
filters out only those that are empty-delete
deletes them.Fine print: -execdir
is not specified by POSIX, though major implementations (at least the GNU and BSD one) support it. If you need strict POSIX compliance, you'll have to make do with the less safe -exec
which would need additional thought to be applied correctly in this case.
Finally, please try your commands in a test directory with dummy files, not your actual data. Especially with the -delete
option of find
, you can loose all your data quicker than you might imaging. Read the man page and, if that is not enough, the reference manual of find
. Never blindly copy shell commands from random strangers posted on the internet if you don't understand them.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments