How do I Remove Specific Characters From File Names Using BASH

Bash

Bash Problem Overview


I have a lot of files that have a shared pattern in their name that I would like to remove. For example I have the files, "a_file000.tga" and "another_file000.tga". I would like to do an operation on those files that would remove the pattern "000" from their names resulting in the new names, "a_file.tga" and "another_file.tga".

Bash Solutions


Solution 1 - Bash

Bash can do sed-like substitutions:

for file in *; do mv "${file}" "${file/000/}"; done

Solution 2 - Bash

Try this (this works in plain old Bourne sh as well):

for i in *000.tga
do
    mv "$i" "`echo $i | sed 's/000//'`"
done

Both arguments are wrapped in quotes to support spaces in the filenames.

Solution 3 - Bash

A non-bash solution, since I know two speedy posters have already covered that:

There's an excellent short perl program called rename which is installed by default on some systems (others have a less useful rename program). It lets you use perl regex for your renaming, e.g:

rename 's/000//' *000*.tga

Solution 4 - Bash

Use rename, maybe you need to install it on linux, Its python script

rename (option) 's/oldname/newname' ...

so you can use it like

rename -v 's/000//' *.tga

that means we are instructing to replace all files with .tga extension in that folder to replace 000 with empty space. Hope that works

You can check this link for more info and here

Solution 5 - Bash

#!/bin/bash
ls | while read name; do
  echo mv $name ${name/$1//}
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
QuestionresolveaswontfixView Question on Stackoverflow
Solution 1 - BashDennis WilliamsonView Answer on Stackoverflow
Solution 2 - BashmouvicielView Answer on Stackoverflow
Solution 3 - BashCascabelView Answer on Stackoverflow
Solution 4 - BashDhruv PalView Answer on Stackoverflow
Solution 5 - BashDigitalRossView Answer on Stackoverflow