find a pattern in files and rename them

LinuxBash

Linux Problem Overview


I use this command to find files with a given pattern and then rename them to something else

find . -name '*-GHBAG-*' -exec bash -c 'echo mv $0 ${0/GHBAG/stream-agg}' {} \;

As I run this command, I see some outputs like this

mv ./report-GHBAG-1B ./report-stream-agg-1B
mv ./reoprt-GHBAG-0.5B ./report-stream-agg-0.5B

However at the end, when I run ls, I see the old file names.

Linux Solutions


Solution 1 - Linux

You are echo'ing your 'mv' command, not actually executing it. Change to:

find . -name '*-GHBAG-*' -exec bash -c 'mv $0 ${0/GHBAG/stream-agg}' {} \;

Solution 2 - Linux

I would suggest using the rename command to perform this task. rename renames the filenames supplied according to the rule specified as a Perl regular expression.

In this case, you could use:

rename 's/GHBAG/stream-agg/' *-GHBAG-*

Solution 3 - Linux

In reply to anumi's comment, you could in effect search recursively down directories by matching '**':

rename 's/GHBAG/stream-agg/' **/*-GHBAG-*

Solution 4 - Linux

This works for my needs, replacing all matching files or file types. Be warned, this is a very greedy search

# bashrc
function file_replace() {
  for file in $(find . -type f -name "$1*"); do
    mv $file $(echo "$file" | sed "s/$1/$2/");
  done
}

I will usually run with find . -type f -name "MYSTRING*" in advance to check the matches out before replacing.

For example:

file_replace "Slider.js" "RangeSlider.ts"

renamed:    packages/react-ui-core/src/Form/Slider.js -> packages/react-ui-core/src/Form/RangeSlider.ts
renamed:    stories/examples/Slider.js -> stories/examples/RangeSlider.ts

or ditch the filetype to make it even greedier

file_replace Slider RangeSlider

renamed:    packages/react-ui-core/src/Form/Slider.js -> packages/react-ui-core/src/Form/RangeSlider.js
renamed:    stories/examples/Slider.js -> stories/examples/RangeSlider.js
renamed:    stories/theme/Slider.css -> stories/theme/RangeSlider.css

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
QuestionmahmoodView Question on Stackoverflow
Solution 1 - LinuxkamituelView Answer on Stackoverflow
Solution 2 - LinuxanumiView Answer on Stackoverflow
Solution 3 - LinuxZacView Answer on Stackoverflow
Solution 4 - Linuxlfender6445View Answer on Stackoverflow