0

I set up the following folders with empty text files:

1/a.txt
2/b.txt

I want to copy only txt files to another directory while maintaining their directory structure. So I tried the following commands:

mkdir -p temp/s;
find ./ -name '*txt' -exec cp --parents '{}' ./temp/s \;

Now I see the following files from my current directory:

1/a.txt
2/b.txt
temp/s/1/a.txt
temp/s/2/b.txt
temp/s/temp/s/2/b.txt

I don't understand why the final line temp/s/temp/s/2/b.txt occurred. Can someone explain to me why that happened and how I can fix my command such that temp is not nested within another temp ?

This is the final result that I was expecting:

1/a.txt
2/b.txt
temp/s/1/a.txt
temp/s/2/b.txt
John
  • 7,343
  • 23
  • 63
  • 87

1 Answers1

2

You have a race condition: since temp/s is in find's search path, find is listing files, while the spawned cps are adding new files.

You have to exclude the sub-directory while running find:

find . -path ./temp/s -prune -o -name '*txt' -exec cp --parents '{}' ./temp/s \;

Note that replacing \; with + will spawn much less cp processes.

Piotr P. Karwasz
  • 5,748
  • 2
  • 11
  • 21