name : add name_replace.

This commit is contained in:
Dmitry Voronin 2023-11-30 06:07:01 +03:00
parent cd6d71a444
commit ed39fa7be9
2 changed files with 49 additions and 0 deletions

View file

@ -559,6 +559,7 @@ Command|Description
`name_ext <EXTENSION> [FILES]`|Change file extensions. `name_ext <EXTENSION> [FILES]`|Change file extensions.
`name_prefix <OLD> <NEW> [FILES]`|Change file prefix. `name_prefix <OLD> <NEW> [FILES]`|Change file prefix.
`name_postfix <OLD> <NEW> [FILES]`|Change file postfix. `name_postfix <OLD> <NEW> [FILES]`|Change file postfix.
`name_replace <OLD> <NEW> [FILES]`|Replace a part of file name.
## Ncdu. ## Ncdu.

View file

@ -427,5 +427,53 @@ name_postfix()
fi 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 for parallel.
export -f name name_hash name_hash_check name_ext export -f name name_hash name_hash_check name_ext