It's a fairly small change, so it'd be nice to include that feature:
从 bash 开始,我们需要一个实用函数 abspath(或绝对路径)
没有这样的内置。
abspath () { case "$1" in
/*)printf "%s\n" "$1";;
*)printf "%s\n" "$PWD/$1";;
esac; }
一旦我们有了它,我们就可以为
Sed/重命名模式,包括新的文件夹结构。
This will ensure we know the names of our target folders. When we
我们需要在目标文件名上使用它。
# generate the rename target
target="$(sed $sed_pattern <<< $file)"
# Use absolute path of the rename target to make target folder structure
mkdir -p "$(dirname $(abspath $target))"
# finally move the file to the target name/folders
mv -v "$file" "$target"
这是完整的文件夹感知脚本..。
sedrename() {
if [ $# -gt 1 ]; then
sed_pattern=$1
shift
for file in $(ls $@); do
target="$(sed $sed_pattern <<< $file)"
mkdir -p "$(dirname $(abspath $target))"
mv -v "$file" "$target"
done
else
echo "usage: $0 sed_pattern files..."
fi
}
当然,如果我们没有特定的目标文件夹,它仍然可以工作
也是。
If we wanted to put all the songs into a folder, ./Beethoven/ we can do this:
用法
sedrename 's|Beethoven - |Beethoven/|g' *.mp3
before:
./Beethoven - Fur Elise.mp3
./Beethoven - Moonlight Sonata.mp3
./Beethoven - Ode to Joy.mp3
./Beethoven - Rage Over the Lost Penny.mp3
after:
./Beethoven/Fur Elise.mp3
./Beethoven/Moonlight Sonata.mp3
./Beethoven/Ode to Joy.mp3
./Beethoven/Rage Over the Lost Penny.mp3
额外奖励。
Using this script to move files from folders into a single folder:
假设我们想收集所有匹配的文件,然后把它们放在
在当前文件夹中,我们可以这样做:
sedrename 's|.*/||' **/*.mp3
before:
./Beethoven/Fur Elise.mp3
./Beethoven/Moonlight Sonata.mp3
./Beethoven/Ode to Joy.mp3
./Beethoven/Rage Over the Lost Penny.mp3
after:
./Beethoven/ # (now empty)
./Fur Elise.mp3
./Moonlight Sonata.mp3
./Ode to Joy.mp3
./Rage Over the Lost Penny.mp3
关于 sed 正则表达式模式的注释
Regular sed pattern rules apply in this script, these patterns aren't
PCRE (Perl 兼容正则表达式)
扩展的正则表达式语法,使用 sed -r或 sed -E
取决于你的平台。
有关。的完整描述,请参阅符合 POSIX 的 man re_format
Sed 基本和扩展的 regexp 模式。