user2141046 user2141046 - 1 month ago 8
Linux Question

How to use find to make copies of file with prefix in CSH?

I am trying to make copies of certain file and let them have a prefix.
in order to do it I thought of using

find
. for our use, let's call them kuku files and I want them to have a "foo" prefix:

find . -maxdepth 1 -name "kuku*" -exec cp '{}' foo_'{}' \;


but it doesn't work because the find always starts the results with ./ so i get a lot of error messages saying "cp: cannot create regular file `foo_./kuku...`: No such file or directory".

the problem is solvable by using foreach f (`ls`) and than using grep and the status var, but it is cumbersome and I want to learn a better solution (and improve my knowledge of the find command along the way...).

update foreach solution (which I don't like and want your help in finding a replacement):

foreach f (`ls`)
echo $f | grep -lq kuku
if (! $status) then
cp $f foo_$f
endif
end


but this is UGLY! (end of update)

as the header says, I'm using csh - not because I love it, just because that's what we use at work...

update
trying to use
basename
as a solution, because
find -exec basename '{}' \;
removes the ./ prefix, but i failed using the basename inside the find with backticks (`), meaning that

find -name "kuku*" -exec cp '{}' foo_`basename '{}` \;


simply doesn't work.

Answer

Here you go.. I have tested in my linux box

find . -name "kuku*" -exec sh -c 'cp {} foo_`basename {}`' \;