I want to go through a bunch of directories and rename all files that end in _test.rb to end in _spec.rb instead. It's something I've never quite figured out how to do with bash so this time I thought I'd put some effort in to get it nailed. I've so far come up short though, my best effort is:
find spec -name "*_test.rb" -exec echo mv {} `echo {} | sed s/test/spec/` \;
NB: there's an extra echo after exec so that the command is printed instead of run while I'm testing it.
When I run it the output for each matched filename is:
mv original original
i.e. the substitution by sed has been lost. What's the trick?
Rename Multiple Files with the mv Command Next, -exec executes the mv command on any files that match the search, changing their current filenames to the new one. Another method is to use the mv command as a part of a <strong>for</strong> loop in a bash script.
Use the move (mv) command on Linux to rename files and folders. The system understands renaming files as moving the file or folder from one name to another, hence why the mv command can be used for renaming purposes, too.
To solve it in a way most close to the original problem would be probably using xargs "args per command line" option:
find . -name "*_test.rb" | sed -e "p;s/test/spec/" | xargs -n2 mv
It finds the files in the current working directory recursively, echoes the original file name (p
) and then a modified name (s/test/spec/
) and feeds it all to mv
in pairs (xargs -n2
). Beware that in this case the path itself shouldn't contain a string test
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With