diff --git a/.README.md b/.README.md index 23c2d23..548d488 100644 --- a/.README.md +++ b/.README.md @@ -559,6 +559,7 @@ Command|Description `name_ext [FILES]`|Change file extensions. `name_prefix [FILES]`|Change file prefix. `name_postfix [FILES]`|Change file postfix. +`name_replace [FILES]`|Replace a part of file name. ## Ncdu. diff --git a/.config/bash/module/name.sh b/.config/bash/module/name.sh index 2d74f4c..24a471b 100644 --- a/.config/bash/module/name.sh +++ b/.config/bash/module/name.sh @@ -427,5 +427,53 @@ name_postfix() fi } +# Replace part of the name. +name_replace() +{ + local IFS=$'\n' + local old="${1}" # Old postfix. + local new="${2}" # New postfix. + local targets=("${@:3}") # Target files. + local count=0 # Total files processed. + local total=$((${#}-2)) # Total files to process. + local failed=0 + + # All targets by default. + if [[ "${targets}" = "" ]]; then + targets=(*${old}*) + total=${#targets[@]} + fi + + # Process. + for target in "${targets[@]}"; do + # Increment counter. + ((count++)) + + # Create new name. + local new_name="${target//$old/$new}" + + # Prepare status. + local status="[${count}/${total}] ${target} -> ${new_name}" + echo -e "${status}" + + # Warning on no change. + [[ "${target}" = "${new_name}" ]] && continue + + # Rename. + mv -- "${target}" "${new_name}" + + if [[ ${?} != 0 ]]; then + echo -e "${color_bred}${status}: Failed.${color_default}" + ((failed++)) + fi + done + + if [[ ${failed} != 0 ]]; then + echo -e "${color_bred}Failed: ${failed}.${color_default}" + false + fi + +} + # export for parallel. export -f name name_hash name_hash_check name_ext