Find a template in files and rename them

I use this command to search for 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}' {} \; 

When I run this command, I see some output, such as

 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.

+52
linux bash
Mar 08 '13 at 9:01
source share
4 answers

You are executing the "mv" echo command, not executing it. Change to:

 find . -name '*-GHBAG-*' -exec bash -c 'mv $0 ${0/GHBAG/stream-agg}' {} \; 
+76
Mar 08 '13 at 9:02
source share

I would suggest using the rename command to complete this task. rename renames the file names provided according to the rule specified as the Perl regular expression.

In this case you can use:

 rename 's/GHBAG/stream-agg/' *-GHBAG-* 
+34
Mar 08 '13 at 9:06 on
source share

In response to anumi's comment, you can search recursively down the directories by matching "**":

 rename 's/GHBAG/stream-agg/' **/*-GHBAG-* 
+17
Aug 20 '13 at 3:46
source share

This works for my needs, replacing all suitable files or file types. Be careful, 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*" find . -type f -name "MYSTRING*" in advance to check for matches 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 cut the file type to make it even more greedy

 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 
+1
Jul 06 '17 at 1:37 on
source share



All Articles