1

I am trying to write a script to copy all files in a directory tree to another directory, using find command. However, some files have the same name as other. Since I am not interested in file names at all, I thought that the simplest solution would be to give to the copies progressive numbers as names. I tried with this command:

i=0

find . -iname "*.jpg" -exec  cp {} $DEST_DIR/$i ; i=$i+1;

however, this command obviously won't work, as -exec runs a subshell in which i variable is not defined. Has anyone got some idea to do this, preferably with find? Is there any other better way to do it?

Ajeje
  • 396
  • 2
  • 5

1 Answers1

1
i=0; find . -iname "*.jpg" | while IFS= read -r f; do echo "$f" "$i"; i=$((i + 1)); done

... assuming there are no files with spaces in their name and such

chepner
  • 497,756
  • 71
  • 530
  • 681
thrig
  • 676
  • 4
  • 11
  • 1
    This should work for any newline-free file names, and that case can be handled with careful use of `-print0` and adjusting the `read` command. (I think `IFS= read -d '' -r f` is sufficient.) – chepner Aug 28 '15 at 16:34
  • The leading `i=0` is not all that useful if the increment happens before use (files start at 1). It won't get changed by the loop. – Etan Reisner Aug 28 '15 at 17:25