Remove underscores from all filenames within a directory Remove underscores from all filenames within a directory unix unix

Remove underscores from all filenames within a directory


This will correctly process files containing odd characters like spaces or even newlines and should work on any Unix / Linux distribution being only based on POSIX syntax.

find model -type f -name "*_*" -exec sh -c 'd=$(dirname "$1"); mv "$1" "$d/$(basename "$1" | tr -d _)"' sh {} \;

Here is what it does:

For each file (not directory) containing an underscore in its name under the model directory and its subdirectories, rename the file in place with all the underscores stripped out.


You can do this simply with bash.

for file in /path/to/model/*; domv "$file" "${file/_/}"done

If you have rename command available then simply do

rename 's/_//' /path/to/model/*


for f in model/* ; do mv "$f" `echo "$f" | sed 's/_//g'` ; done

Edit: modified a few things thanks to suggestions by others, but I'm afraid my code is still bad for strange filenames.