Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

This is what I have so far.

#!/bin/bash

pushd DirectoryName

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

popd
share|improve this question
add comment

1 Answer

I would use the following:

#! /bin/bash
cd DirectoryName
for file in *.csv; do
    filename=${file%.*}
    file_clean=`echo $filename | tr -cs "[:alnum:]_" _ `
    final="$file_clean.csv"
    echo "mv \"$file\" \"$final\" "
done
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
1  
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
add comment

Your Answer

 
discard

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.