6

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.

4

4 回答 4

4

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

tar -C 0001 -cf - --transform 's/\(.\+\)\.[^.]\+$/\1/' . |
tar -C 0002 -xf -
于 2012-09-25T18:43:57.827 回答
2

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)!

于 2012-09-25T20:37:14.870 回答
1

Here's some find + bash + install that will do the trick:

for src in `find 0001 -type f`  # for all files in 0001...
do
  dst=${src/#0001/0002}         # match and change beginning of string
  dst=${dst%.*}                 # strip extension
  install -D $src $dst          # copy to dst, creating directories as necessary
done

This will change the permission mode of all copied files to rwxr-xr-x by default, changeable with install's --mode option.

于 2012-09-25T20:58:11.690 回答
0

I came up with this ugly duckling:

find 0001 -type d | sed 's/^0001/0002/g' | xargs mkdir
find 0001 -type f | sed 's/^0001//g' | awk -F '.' '{printf "cp -p 0001%s 0002%s\n", $0, $1}' | sh

The first line creates the directory tree, and the second line copies the files. Problems with this are:

  1. There is only handling for directories and regular files (no symbolic links etc.)
  2. If there are any periods (besides the extension) or special characters (spaces, etc.) in the filenames then the second command won't work.
于 2012-09-25T20:03:13.293 回答