1

How can I make this command also execute throughout sub directories?

for filename in *foo*; do mv "$filename" "${filename//foo/bar}"; done
  • Have you tried, using the globstar pattern `**` to recurse into subdirectories like so: `**/*foo*`? You may have to enable this feature before you can use it: `shopt -s globstar`. – Xoozee Dec 03 '21 at 09:44
  • Set the `globstar` option by `shopt -s globstar` and then replace the `*foo*` with `**/*foo*`. – M. Nejat Aydin Dec 03 '21 at 09:48
  • Note, though, that you should check, whether this does what you expect, e.g. by putting an `echo` before the `mv`. – Xoozee Dec 03 '21 at 09:49
  • Like Xoozee said, or at least do a `mv -iv ....`. – user1934428 Dec 03 '21 at 09:50

1 Answers1

1

Probably you want to rename only the filename (last pathname component), not a inbetween subdirectory name. Then this task can be accomplished using globstar feature of bash.

#!/bin/bash

shopt -s globstar
for pathname in ./**/*foo*; do
    [[ -f $pathname ]] || continue
    basename=${pathname##*/}
    mv "$pathname" "${pathname%/*}/${basename//foo/bar}"
done
M. Nejat Aydin
  • 9,597
  • 1
  • 7
  • 17