问题描述
Jeff Smith 1.png
Jeff Donald 1.png
Jeff Donald 2.png
Jeff Smith 2.png
Jeff Roberts.png
Kyle Reds.png
Kyle Reds 1.png
Kyle Blues 1.png
Kyle Blues 2.png
Kyle Person.png
etc
etc
我如何编写一个bash脚本,该脚本可以为每个唯一名称创建一个文件夹。
对于上面的示例,我们将获得文件夹:
Jeff Smith
Jeff Donald
Kyle Reds
Kyle Blues
Kyle Person
etc
我是bash的新手(通常是编码)-希望对此有所帮助
谢谢
解决方法
您可以执行以下操作:
- 列出目录中的文件,用
sed
删除枚举和扩展名后缀,并将其分配给变量
prefixes_png=$(ls | sed -r 's/\s?[0-9]*\.\w+$//')
- 对行进行排序并删除重复的行
unique_prefixes=$(echo "$prefixes_png" | sort -u)
- 遍历名称,为每个名称创建一个匹配的目录
echo "$unique_prefixes" | while read prefix
do
mkdir "$prefix"
done
,
标准实用程序或纯Bash:您拨打电话!
如果您不需要纯Bash解决方案,则可以使用标准实用程序,例如find,sed和sort。例如:
find . -maxdepth 1 -type f -name \*.png |
sed 's!^\./!!; s/[[:space:]]*[[:digit:]]*\.[Pp][Nn][Gg]//' |
sort -u |
xargs -I{} mkdir "{}"
这很好用,非常紧凑,如果您可以通过sed中的正则表达式,则相对容易理解。您也可以在纯Bash中使用一些shell options,一个associative array和一些shell expansions来完成此操作。例如:
# make shell globs case insensitive
shopt -s nocaseglob
# turn on extended globs for more advanced pattern matching
shopt -s extglob
# associative array ensures names (keys) are unique
declare -A names
# create empty key for each name extracted from a filename
for file in *.png; do
names["${file%%*([[:space:]])*([[:digit:]]).png}"]=
done
# create a directory for each key in the array
for name in "${!names[@]}"; do
mkdir "$name"
done
# revert shell options
shopt -u extglob
shopt -u nocaseglob
两种解决方案都可以使用。标准实用程序可能会更快,并且(IMHO)易于调整,而仅Bash版本避免了调用任何外部命令的需要。哪一个最适合您的用例完全取决于您!