How to Append a String to a File Name in Bash Shell?

So I am supposed to find all the files in the given directory with surffix of .C or cc, and change their name to .C.blah or .cc.blah

Is there a command to do that?

Or should I implement this with the command find?

3

4 Answers

There are a few approaches, depending on what is available on your *nix.

There two different rename commands around, one provided through perl, and one as part of standard utils.

Perl version:

rename 's/(\.cc$|\.C$)/$ *.cc *.C

utils version - you might be able to do this with one line:

rename .C .C.blah *.C
rename .cc .cc.blah *.cc

for loop:

for i in *.C *.cc ; do mv $i $i.blah ; done

use a simple for-loop:

for file in *.txt; do echo $file $file.blah; done

This command echoes the old file name and the new file to the terminal. If you're getting expected results, go for the real command:

for file in *.txt; do mv $file $file.blah; done

Anyway, this won't rename *.txt files in subdirectories. Use find for it.

I know you already found your own acceptable solution, but I want to post what I would normally use at work. This syntax works for GNU findutils, which is part of any modern linux distro.

## xargs is much faster than -exec, xargs can run parallel on # cores with -P #
find ./ -type f -name '*.C' -o -name '*.cc' | xargs -I '{}' mv '{}' '{}'.BAK

##  If I'm specifying more than two extensions, I would generally use a regex
find ./ -type f -regex ".*\.\(C\|cpp\)$" | xargs -I '{}' mv '{}' '{}'.BAK

Especially with the now common quad-core SMP servers, you can usually half running time with -p 4. Even with only one core, xargs avoids the extraneous forking find ...-exec would initiate. With a desktop, and unlimited time, it's not really a problem. On the other hand using server resources, and working with many thousands of files, avoiding unnecessary overhead is a priority.

There are two different rename commands.

On Ubuntu/Debian/... distros:

rename -v 's/$/.blah/' *.C *.cc

On RedHat/CentOS/... distros:

rename -v $ .blah *.C *.cc

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sophia Al-Mansoor

Sophia Al-Mansoor

Global Business & E-Commerce Reporter

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.

Share this article
Twitter Facebook Pinterest