Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use find to copy and remove extensions keeping the same subdirectory structure [closed]

I'm trying to copy all the files from one directory to another, removing all file extensions at the same time.

From directory 0001:
 0001/a/1.jpg
 0001/b/2.txt

To directory 0002:
 0002/a/1
 0002/b/2

I've tried several find ... | xargs c...p with no luck.

like image 607
Lokus Pokus Avatar asked Sep 25 '12 18:09

Lokus Pokus


2 Answers

Recursive copies are really easy to to with tar. In your case:

tar -C 0001 -cf - --transform 's/\(.\+\)\.[^.]\+$/\1/' . |
tar -C 0002 -xf -
like image 57
nosid Avatar answered Oct 02 '22 02:10

nosid


If you haven't tar with --transform this can works:

TRG=/target/some/where
SRC=/my/source/dir
cd "$SRC"
find . -type f -name \*.\* -printf "mkdir -p '$TRG/%h' && cp '%p' '$TRG/%p'\n" |\
   sed 's:/\.::;s:/./:/:' |\
   xargs -I% sh -c "%"

No spaces after the \, need simple end of line, or you can join it to one line like:

find . -type f -name \*.\* -printf "mkdir -p '$TRG/%h' && cp '%p' '$TRG/%p'\n" | sed 's:/\.::;s:/./:/:' | xargs -I% sh -c "%"

Explanation:

  • the find will find all plain files what have extensions in you SRC (source) directory
  • the find's printf will prepare the needed shell commands:
    • command for create the needed directory tree at the TRG (target dir)
    • command for copying
  • the sed doing some cosmetic path cleaning, (like correcting /some/path/./other/dir)
  • the xargs will take the whole line
  • and execute the prepared commands with shell

But, it will be much better:

  • simply make an exact copy in 1st step
  • rename files in 2nd step

easier, cleaner and FASTER (don't need checking/creating the target subdirs)!

like image 28
kobame Avatar answered Oct 02 '22 03:10

kobame