Skip to content

Instantly share code, notes, and snippets.

@KR1470R
Last active May 7, 2022 14:25
Show Gist options
  • Save KR1470R/477c931da309feb2b999fb009cfdfc12 to your computer and use it in GitHub Desktop.
Save KR1470R/477c931da309feb2b999fb009cfdfc12 to your computer and use it in GitHub Desktop.
Use this script to massive file renaming or conservation(as copy prefix in name of file) files in specific directory
#!/usr/bin/env sh
trap 'echo "Usage: $0 path/to/folder {copy|replace} \"old_name|new_name\""' 0
export path=${1?"File to path wasn't specified!"};shift
export status=${1?"Status wasn't specified!"};shift
if [[ -z "$@" ]]; then
echo "Name files wasn't specified!"
exit 1
else
# exmpl "name1part1 name1part2|name2part1 name2part2"
if test $(echo $@ | tr -cd "|" | wc -c) -eq "1"; then
export name=$(echo $@ | cut -d "|" -f 1)
export goal_name=$(echo $@ | cut -d "|" -f 2)
if [[ -z $name ]]; then echo "Couldn't recognize file name!";exit 1; fi
if [[ -z $goal_name && $status == "replace" ]]; then echo "Couldn't recognize file goal name!";exit 1; fi
else
echo "Bad syntax in $@"
exit 1
fi
fi
export goal_files=$(ls $path | grep "$name")
if [[ -z $goal_files ]]; then
echo "Goal files list is empty. Exiting..."
exit 1
fi
export IFS=$'\n'
echo "Status - $status"
for filename in $goal_files; do
if [[ $status == "copy" ]]; then
result_filename="copy_$filename"
echo "Copying $filename into $result_filename ..."
cp "$path/$filename" "$path/$result_filename"
elif [[ $status == "replace" ]]; then
file_id=$(echo $filename | cut -d "." -f 1)
file_type=$(echo $filename | cut -d "." -f 3-4)
result_filename="$file_id.$goal_name.$file_type"
echo "Moving $filename into $result_filename ..."
mv "$path/$filename" "$path/$result_filename"
else
echo "Uknown status!"
exit 1
fi
done
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment