Search code examples
linuxmv

Rename All Files in directory and subdirectories Linux


I've searched many times in other Questions and i did not finded the answer ,

I need to rename a part of file names in a folder and all of subdirectories on that folder .

I've found the right CMD , but it just works for files in current dir , how can i use this for Rename fiels in all sub directories too ?

for filename in *mohsen*; do echo mv \"$filename\" \"${filename//mohsen/bar}\"; done | /bin/bash

THank you


Solution

  • you can use a tool like mmv to achieve that, or a more modern, nicer way would be to use pythonpy:

    % find -regex '.*mohsen.*' | py -x '"mv `{}` `{}`".format(x,re.sub("mohsen", "foo", x)' | sh
    

    as you say you cannot use python (WTF?!?!?), here's another option:

    something like:

    for filename in $(find -regex '.*mohsen.*'); do echo mv \"$filename\" \"${filename//mohsen/bar}\"; done | /bin/bash
    

    but that will fail with files that have spaces, so you might need to use:

    OLDIFS="$IFS" IFS=$'\n' for filename in $(find -regex '.*mohsen.*'); do echo mv \"$filename\" \"${filename//mohsen/bar}\"; done | /bin/bash; IFS="$OLDIFS"
    

    in order to setup line delimiters to only the carriage return and not the spaces. Beware that's an ugly non-recommended option to do it, which is fine for a "one time" use, but don't use that in a script.

    Also, once you're happy with the output using "echo" in the commands I gave, remove the echo and run it.