Reputation: 191
Is it possible to change the parameters that are passed to exec in find? For example I need to copy files under a different names: *.txt -> *.new.txt Now I'm doing it for two commands:
find /root/test -name "*.txt" -exec cp {} {}.new \;
find /root/test -name "*.txt.new" -exec rename .txt.new .new.txt {} \;
Is it possible to parse {} to access the file extension? Something like (i don't know exactly):
-exec cp {} {$1}.new.txt \;
Upvotes: 3
Views: 705
Reputation: 5674
I'm not sure if it's possible doing what you're asking exactly, but it's certainly possible to perform that kind of modification to the parameter using the shell:
find /root/test -name "*.txt" -exec sh -c 'cp "$0" "${0%.txt}.new.txt"' "{}" \;
I'll try to break this down so it's a little more understandable:
-exec sh -c '<...>' "{}" \;
This starts a new shell which executes the script specified in single quotes. Also note that "{}"
is a parameter sent to this script and will be available as $0
within that script.
As for the script itself, $0
is the matched text file, and we copy that to ${0%.txt}.new.txt
which takes the file name ($0
), and trims the first text that matches .txt
from the END of the file name, leaving us with a file name without an extension. Then we simply append the new file name .new.txt
.
As an addendum, depending on what your system is like, you may get a "substitution error" message (I got this on my Mint install, but not on my CentOS install). If you do, try to change -exec sh
to -exec bash
.
Upvotes: 3