Skip to content

Instantly share code, notes, and snippets.

@Rami-Majdoub
Created March 17, 2023 10:21
Show Gist options
  • Save Rami-Majdoub/39d522a893a46069699fa363470686bb to your computer and use it in GitHub Desktop.
Save Rami-Majdoub/39d522a893a46069699fa363470686bb to your computer and use it in GitHub Desktop.
Rename files
#!/bin/bash
# BASEDIR=$1;
# for file in `ls -1 $BASEDIR*.{jpeg}`; do
# echo "$file" "$(date -r "$BASEDIR/$file" +"%Y-%m-%d_%H-%M-%S").jpg"
# done
# ls | egrep '\.mp4$|\.mp3$|\.exe$'
# for file in `ls -1 $BASEDIR | egrep '\.jpeg$'`; do
# | sed 's/ //g'
# escape space in files
# https://www.cyberciti.biz/tips/handling-filenames-with-spaces-in-bash.html
SAVEIFS=$IFS
IFS=$(echo -en "\n\b")
BASEDIR=$1;
EXTENSION=$2
REGEX="\.$EXTENSION$"
for file in `ls -1 $BASEDIR | grep "$EXTENSION"`; do
OLD_FILE_NAME="$file"
NEW_FILE_NAME=$(date -r "$BASEDIR/$file" +"%Y-%m-%d_%H-%M-%S")
if [[ "$file" != ????-??-??'_'??-??-??* ]]; then
if [[ ! -f "$BASEDIR/$NEW_FILE_NAME.$EXTENSION" ]]; then
echo "$OLD_FILE_NAME => $NEW_FILE_NAME";
mv -n "$BASEDIR/$file" "$BASEDIR/$NEW_FILE_NAME.$EXTENSION";
else
index=1
while [ -f "$BASEDIR/${NEW_FILE_NAME}_${index}.$EXTENSION" ];
do
index=$(( $index + 1 ))
done
echo "$OLD_FILE_NAME => ${NEW_FILE_NAME}_${index}";
mv -n "$BASEDIR/$file" "$BASEDIR/${NEW_FILE_NAME}_${index}.$EXTENSION";
fi;
fi;
done
# restore settings
IFS=$SAVEIFS
#!/bin/bash
# escape space in files
# https://www.cyberciti.biz/tips/handling-filenames-with-spaces-in-bash.html
SAVEIFS=$IFS
IFS=$(echo -en "\n\b")
BASEDIR=$1;
EXTENSION=$2
REGEX="\.$EXTENSION$"
index=0
for file in `ls -1 $BASEDIR | grep ".$EXTENSION"`; do
index=$(( $index + 1 ))
OLD_FILE_NAME="$file"
NEW_FILE_NAME=$index
echo "$OLD_FILE_NAME => $NEW_FILE_NAME";
mv -n "$BASEDIR/$file" "$BASEDIR/$NEW_FILE_NAME.$EXTENSION";
done
# restore settings
IFS=$SAVEIFS
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment