Q . Find and Replace in filenames using command line.

Dev Singh. asked, Jul 25 ' 2017

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.

  • terminal
  • find-and-replace
  • filenames

2 Answers

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/<find>/<replace>/g' <file-name>

#example : 
rename 's/GHBAG/stream-agg/g' *-GHBAG-*

 

Leave a Ansewer