Skip to content

Instantly share code, notes, and snippets.

@kaxing
Last active April 28, 2024 05:59
Show Gist options
  • Save kaxing/3c926b6af4f3cbd7bbb33709036748a7 to your computer and use it in GitHub Desktop.
Save kaxing/3c926b6af4f3cbd7bbb33709036748a7 to your computer and use it in GitHub Desktop.
Batch filename conversion to zh_TW from zh_CN 批次檔名轉繁體

The entire script is generated with gpt-4-turbo on 2024-April-28; This script won't work without https://github.com/BYVoid/OpenCC

Usage:

./convert2zhtw.sh .

or append suffix,

./convert2zhtw.sh . "_content_in_simplified_characters"

Please be aware when append suffix, the filename duplication checking will no longer works. E.g., ABC -> ABC_new -> ABC_new_new.


此sciprt是透過GPT-4 Turbo產出。必須搭配OpenCC指令來使用。 將簡體檔案、目錄名稱轉換成繁體(不包含內容)。

使用方式:

./convert2zhtw.sh .

可以替檔名加上後綴:

./convert2zhtw.sh . "_內容是簡體"

注意加上suffix會無法比較重複的檔名,如果跑兩次以上會變成: 這是繁體 -> 這是繁體_內容是簡體 -> 這是繁體_內容是簡體_內容是簡體

#!/bin/bash
# ANSI color codes
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
NC='\033[0m' # No Color
# Function to display usage information
usage() {
echo -e "Usage: $0 <directory or file> [append_suffix(optional)]"
echo "Converts filenames from Simplified to Traditional Chinese using OpenCC."
echo "Optionally appends a suffix to file names, preserving extensions. The suffix is optional."
exit 1
}
# Check if opencc is installed
if ! command -v opencc &> /dev/null; then
echo -e "${RED}opencc could not be found. Please install opencc from https://github.com/BYVoid/OpenCC to use this script.${NC}"
exit 2
fi
# Check if an argument is provided, if not, display usage
[[ $# -eq 0 ]] && usage
# Set the target path and optional suffix
target_path="$1"
suffix="${2:-}" # Suffix is optional and can be empty
echo "Starting conversion for: $target_path with optional suffix '$suffix'"
# Function to convert name using opencc
convert_name() {
echo "$1" | opencc -c s2tw.json
}
# Function to recursively rename items
rename_items() {
local path="$1"
# Using find to list all files, ignoring directories for renaming
find "$path" -depth -type f | while IFS= read -r item; do
local dir=$(dirname "$item")
local base=$(basename "$item")
local name="${base%.*}"
local ext="${base##*.}"
local converted_name=$(convert_name "$name")
# Append suffix only if not empty and handle extensions
if [[ -n "$suffix" ]]; then
converted_name="${converted_name}${suffix}"
fi
if [[ "$name" != "$base" ]]; then # File has an extension
converted_name="${converted_name}.${ext}"
else # File has no extension
converted_name="${converted_name}"
fi
# Perform renaming only if new and old names differ
if [[ "$base" != "$converted_name" ]]; then
echo -e "${GREEN}Renaming '$base' to '$converted_name'${NC}"
mv -v "$item" "$dir/$converted_name"
else
echo -e "${YELLOW}Skipping: $item (no name change)${NC}"
fi
done
}
# Execute the renaming
rename_items "$target_path"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment