nagualcode
nagualcode

Reputation: 57

BASH: Raplace filenames characters that are not on list

I want to create a list:

0123456789abcdefghijklmnopqrstuvxwyzABCDEFGHIJKLMNOPQRSTUVXWYZ-._

And then iterate trough all files in folder, replacing every character in the file names that is not present in this list with an underscore _.

That includes blank spaces.

But using Bash and GNU tools only.

Is that possible?

Upvotes: 3

Views: 93

Answers (3)

hek2mgl
hek2mgl

Reputation: 158060

Having the Perl version of the rename command, you can use this:

rename 's/[^[:alnum:]._-]/_/g' *

Upvotes: 4

tripleee
tripleee

Reputation: 189577

Bash internals only:

for file in *; do
    repl=${file//[!$permitted]/_}
    case $file in "$repl") continue;; esac  # skip if identical
    # Safety: add a suffix to avoid overwriting
    while [ -e "$repl" ]; do
        repl=${repl}_
    done
    mv "$file" "$repl"
done

If $permitted contains a slash, you will need to backslash-escape it.

Upvotes: 7

cadrian
cadrian

Reputation: 7376

Yes it is possible :)

for filename in *; do
    newfilename=$(echo "$filename" | sed 's/[^0123456789abcdefghijklmnopqrstuvxwyzABCDEFGHIJKLMNOPQRSTUVXWYZ._-]/_/g')
    mv "$filename" "$newfilename"
done

Upvotes: 0

Related Questions