gpt4 book ai didi

linux - Linux下文件名转换的Shell脚本

转载 作者:太空宇宙 更新时间:2023-11-04 05:53:25 26 4
gpt4 key购买 nike

我对 Unix 很陌生,很少接触 shell 脚本。我需要编写一个脚本,将文件名从某些字符串值转换为特殊字符。这需要以这样的方式运行,子目录下的所有文件也会被重命名。

例如:

来自:abc(GE)xyz(PR).txt 更改至:abc>xyz%.txt

我可以为所有必需的特殊字符设置 if 条件,但我不确定要传递哪些选项以及如何为所有子目录执行此操作。

谢谢,杰尔

最佳答案

这是一种方法:

# given a filename, execute any desired replacements.
update_name() {
local orig_name_var=$1
local dest_name_var=$2
local orig_name=${!orig_name_var}
local new_name="$orig_name"

new_name=${new_name//(GE)/">"}
new_name=${new_name//(PR)/"%"} # repeat for additional substitutions

printf -v "$dest_name_var" "$new_name"
}

while IFS= read -r -d '' orig_name; do
update_name orig_name new_name
[[ $orig_name = $new_name ]] && continue

if ! [[ -e $orig_name ]]; then
orig_dirname=${orig_name%/*}
orig_basename=${orig_name##*/}
update_name orig_dirname new_dirname
if [[ -e $new_dirname/$orig_basename ]]; then
# we already renamed the directory this file is in
orig_name=$new_dirname/$orig_basename
fi
fi
mv -- "$orig_name" "$new_name"
done < <(find . '(' -name '*(GE)*' -o -name '*(PR)*' ')' -print0)

关于linux - Linux下文件名转换的Shell脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24543305/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com