Skip to content

Instantly share code, notes, and snippets.

@billspat
Created December 10, 2015 05:20
Show Gist options
  • Save billspat/7e72761471b6602ff9c1 to your computer and use it in GitHub Desktop.
Save billspat/7e72761471b6602ff9c1 to your computer and use it in GitHub Desktop.
simple bash script to replace non-alphanumerics with underscores, probably written a million times before this.
#!/bin/bash
# examine all files names in current directory and emit a 'mv' command to rename
# if the filename has non alphanumeric in it, other than dot or underscore
# first loop all files, could use find for this, since loop isn'te recursive
for f in *.*; do
# if filename has bad chars
if [[ $f =~ [^a-zA-Z0-9_\.] ]]; then
# create new filename with underscores, remove double underscores
newf=`sed 's/[^a-zA-Z0-9_\.]/_/g' <<< $f | sed 's/__/_/g'`
# echo mv command
echo "mv \"$f\" \"$newf\""
fi
done
@billspat
Copy link
Author

To use: save the above file in your path, then

 cd my/folder/with/badiflenames

 # test to see if you like results
 underscorify.sh |less
 # run the emitted 'mv' commands
 underscorify.sh | bash
 # test that all files were found 
 underscorify.sh   # should be blank

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment