Rename multiple files in shell

BashShell

Bash Problem Overview


I have multiple files in a directory, example: linux_file1.mp4, linux_file2.mp4 and so on. How do I move these files, using shell, so that the names are file1.mp4, file2.mp4 and so on. I have about 30 files that I want to move to the new name.

Bash Solutions


Solution 1 - Bash

I like mmv for this kind of thing

mmv 'linux_*' '#1'

But you can also use rename. Be aware that there are commonly two rename commands with very different syntax. One is written in Perl, the other is distributed with util-linux, so I distinguish them as "perl rename" and "util rename" below.

With Perl rename:

rename 's/^linux_//' linux_*.mp4

As cweiske correctly pointed out.

With util rename:

rename linux_ '' linux_*.mp4

How can you tell which rename you have? Try running rename -V; if your version is util rename it will print the version number and if it is perl rename it will harmlessly report and unknown option and show usage.

If you don't have either rename or mmv and don't want to or can't install them you can still accomplish this with plain old shell code:

for file in linux_*.mp4 ; do mv "$file" "${file#linux_}" ; done

This syntax will work with any POSIX sh conforming to XPG4 or later, which is essentially all shells these days.

Solution 2 - Bash

$ rename 's/linux_//' linux_*.mp4

Solution 3 - Bash

A simple native way to do it, with directory traversal:

find -type f | xargs -I {} mv {} {}.txt

Will rename every file in place adding extension .txt at the end.

And a more general cool way with parallelization:

find -name "file*.p" | parallel 'f="{}" ; mv -- {} ${f:0:10}trump${f:4}'

Solution 4 - Bash

I was able to achieve replace filenames within directories by combining @dtrckd and @Sorpigal answers.

for file in `find -name "linux_*.mp4"`; do mv "$file" "${file/linux_/}" ; done

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionelzwhereView Question on Stackoverflow
Solution 1 - BashsorpigalView Answer on Stackoverflow
Solution 2 - BashcweiskeView Answer on Stackoverflow
Solution 3 - BashdtrckdView Answer on Stackoverflow
Solution 4 - BashMrinal SaurabhView Answer on Stackoverflow