0

There is a set of file paths that i need to copy to some other location:

find . -name '*.txt': 
/a/b/c/d/e/f/filea.txt
/a/b/c/d/e/g/h/fileb.txt
/a/b/c/d/e/k/l/filec.txt

I want to copy each of the files to the path that includes e and after e.g:

cp /a/b/c/d/e/f/filea.txt e/f/

The e path will always exists. I need first to find all files. How can find, extract everything after e from the path and copy at the same time?

user847988
  • 984
  • 1
  • 16
  • 30
  • Use one of the `while`/`read` looping solutions from [here](http://stackoverflow.com/a/9612232/258523) and then use whatever tools you want to cut the path and create the copy command. Alternatively, use `find` to find the `e` directories and then just `cp -r` those directories to the target location. – Etan Reisner Jul 10 '15 at 13:03

2 Answers2

1

Pipe the find output through

sed 's|\(.*\)\(\*\*e\*\*.*/\)\(.*\)|cp \1\2\3 \2|' 

and if the result looks ok, pipe the sed output through sh. If by **e** you just meant e, the pattern is

 sed 's|\(.*\)\(e.*/\)\(.*\)|cp \1\2\3 \2|' 
meuh
  • 11,500
  • 2
  • 29
  • 45
  • i think it does not work, it matches everything in the 1st group :(.*\) and there is no second group after. – user847988 Jul 10 '15 at 14:31
  • `.*` does indeed match everything, but then sed backs up until it maches the `**e**` string. Perhaps you just meant `e` and the `**` is just for emphasis? So replace it by your actual `e`. I'll edit the answer. – meuh Jul 10 '15 at 15:04
  • ok great the only problem is that it keeps the filename at the end which is not good it should be cp folder folder. i edited the question. is it possible to remove the filename in the 2nd group? – user847988 Jul 10 '15 at 16:18
0

You can use something like this. If the generated mkdir and cp commands look ok, you can remove the echo before them.

SOURCE="/a/b/c/d"
cd $SOURCE
DESTINATION="full/path/to/whatever"

for FILE in $(find . -name '*.txt'); do

DIR=$(dirname $FILE)  
# create the intermediate directories if they don't exist  

echo "mkdir -p $DESTINATION/$DIR"  

echo "cp $FILE $DESTINATION/$DIR"  

done

ramana_k
  • 1,933
  • 2
  • 10
  • 14