Tuesday, February 22, 2022

[SOLVED] Rename a portion of a filename recursively throughout directory and sub directory

Issue

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

for filename in *foo*; do mv "$filename" "${filename//foo/bar}"; done

Solution

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


Answered By - M. Nejat Aydin
Answer Checked By - Timothy Miller (WPSolving Admin)