find a pattern in files and rename them [closed]

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.


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}' {} \;

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-*

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

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

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