giovedì 10 dicembre 2015

Automatically clean and format a file name for Web in Bash

Hello there!

You want to automatically format and clean a file name before upload on a website?
Do you want to remove spaces, symbol and accents from a filename automatically, or in batch?

These command will strip anything that's not good to have in a web filename and copy your file to the new file! You can rename original file by change last "cp" with "mv"

#!/bin/bash
FILE=$1
# Remove path
FILECLEAN="${FILE##*/}"
# Find extension (sometimes useful)
FILEXT="${FILECLEAN##*.}"
# Find filename without extension

FILENAME="${FILECLEAN%.*}"

# Convert spaces in dash

FILENAME="${FILENAME// /-}"

# Remove symbols and keep dash and underscores

FILENAME="${FILENAME//[^[:alnum:]_-]/}"

# Remove eventual double dashes from filename

FILENAME="$(echo $FILENAME | tr -s '-')"

# First letter uppercase and other lowercase

FILENAME="$(tr '[:lower:]' '[:upper:]' <<< ${FILENAME:0:1})$(tr '[:upper:]' '[:lower:]' <<< ${FILENAME:1})"


cp "$FILE" "$FILENAME"".""$FILEXT"

Save it into a file with .sh extension, then do this to make it executable:
chmod +x file.sh

Execute with:
./file.sh file

You can even bath the process with a script like this:
#!/bin/bash

# Rimuovo i *.jpg etc dalla lista dei FILE

shopt -s nullglob
for FILE in *; do   
   # Remove path
   FILECLEAN="${FILE##*/}"  
   # Find extension (sometimes useful) 
   FILEXT="${FILECLEAN##*.}"   
   # Find filename without extension
   FILENAME="${FILECLEAN%.*}"
   # Convert spaces in dash   
   FILENAME="${FILENAME// /-}"
   # Remove symbols and keep dash and underscores   
   FILENAME="${FILENAME//[^[:alnum:]_-]/}"   
   # Remove eventual double dashes from filename   
   FILENAME="$(echo $FILENAME | tr -s '-')"   
   # First letter uppercase and other lowercase  
    FILENAME="$(tr '[:lower:]' '[:upper:]' <<< ${FILENAME:0:1})$(tr '[:upper:]' '[:lower:]' <<< ${FILENAME:1})"

   cp "$FILE" "$FILENAME"".""$FILEXT"
done

Nessun commento:

Posta un commento