Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

This is what I have so far.


pushd DirectoryName

for file in *.csv; do
    #echo $file
    file_clean=${filename//[ ()$+&\.\-\'\,]/_}
    final= "$file_clean.csv"
    mv "$file" $final

share|improve this question

I would use the following:

#! /bin/bash
cd DirectoryName
for file in *.csv; do
    file_clean=`echo $filename | tr -cs "[:alnum:]_" _ `
    echo "mv \"$file\" \"$final\" "
cd ..

The only changes are:

1) There was a space after the = in the line final= "$file_clean.csv". I have removed it.

2) Instead of using the string substitution command I have used the tr command. With tr, the -c option says to replace any character that is not in the set. So I can specify the characters I want to keep (alphanumerics and the underscore, in this case) and all the others will be transformed.

This should match some more special characters that are hard to specify via direct substitution, such as []\{} and ". The -s option means that only one underscore will be generated even if suppressing multiple characters. Thus abc((((())))).csv translates into abc_.csv instead of abc__________.csv

share|improve this answer
You can do the same as 2) without using the external executable tr: file_clean=${filename//[^[:alnum:]]/_}. You can suppress the runs of multiple characters like this: shopt -s extglob; file_clean=${filename//+([^[:alnum:]])/_} – Dennis Williamson Jun 19 '10 at 1:11
Cool. I didn't know you could use character classes in bash substitutions. Thanks. – Pat Wallace Jun 19 '10 at 12:44
I'd put a -n flag onto the mv command. If you happen to have two filenames which clean up to the same name then you'll overwrite & loose one. – gorilla Sep 21 '10 at 0:57

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.