DEAR PEOPLE FROM THE FUTURE: Here's what we've figured out so far...

Welcome! This is a Q&A website for computer programmers and users alike, focused on helping fellow programmers and users. Read more

What are you stuck on? Ask a question and hopefully somebody will be able to help you out!
+3 votes

I want to recursively remove a substring from all files. I'm trying with the following command but it doesn't work:

❯ find . -name 'foobar*' -exec rename -vn 's/foobar//g' {} \;
rename: not enough arguments
Try 'rename --help' for more information.

I've added the options v and n to print instead of making changes.

I've also tried without the find part with no luck:

rename -nv "foobar" "" *
rename: invalid option -- ' '
Try 'rename --help' for more information.

The rename that I'm using says that it's part of the util-linux package.

I believe this is happening because there are files in the folder that start with a hypen.

edited by

2 Answers

+1 vote
Best answer

You don't have to use rename. This can be done with mv also

for f in *foo* ; do mv $f ${f/foo/bar} ; done

${string/foo/bar} replaces first match of 'foo' with 'bar'. ${string//foo/bar} replaces all matches. Read here String Replacement for a complete explanation.


find . -type f -name '*foo*' | while read FILE ; do
    newname="$(echo ${FILE} | sed -e 's/foo/bar/g')" ;
    mv "${FILE}" "${newname}" ;
selected by
+2 votes

Is rename this rename (the Perl command line tool)? I use it too for renaming files. The string argument that you are supplying is a Perl expression and follows Perl rules.
This will rename all files in the folder, by replacing "foo" with "bar"

rename 's/foo/bar/' *

or with find

find . -type f -exec rename 's/foo/bar/' {} \;

For the other "rename" (util-linux) the syntax is

rename from to files...

without expressions, just plain string matching I believe.

edited by

I don't know how to check if they are the same. The documentation is different so I guess they are not the same. If I install that rename will it overwrite the current rename? And do I want to do that or is it better to give each a different name? If so how?

I've installed it and it gets installed with a different name. So I've tried it with:

find . -type f -name 'foo*' -exec renamexm --yes -tv 's/foo/bar/g' {} \;

but it doesn't print the change so I don't know if it's working.


On Arch the package (and the binary) is called "perl-rename". The other "rename" is another thing and uses its own rules for matching files. The package manager will deal with any conflicts you don't need to rename anything.

Contributions licensed under CC0