bash 根据文件名的第一部分将文件移动到目录?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1251938/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Move files to directories based on first part of filename?
提问by Aevum Decessus
I have several thousand ebooks that need to be organized on a headless linux server running bash through SSH. All of the ebooks are thankfully named with one of 2 conventions.
我有几千本电子书需要在通过 SSH 运行 bash 的无头 linux 服务器上进行组织。谢天谢地,所有电子书都以两种约定之一命名。
- AuthorFirstName AuthorLastName - Book Title.pdf
- AuthorFirstName AuthorLastName - Book Series #inSeries - Book Title.pdf
- AuthorFirstName AuthorLastName - 书名.pdf
- AuthorFirstName AuthorLastName - 图书系列 #inSeries - 书名.pdf
What I would like to do is to move all of the books into an organized system such as:
我想做的是将所有书籍移动到一个有组织的系统中,例如:
`DestinationDirectory/FirstLetterOfAuthorFirstName/Author Full Name/pdf's`
e.g. the following books
例如以下书籍
Andrew Weiner - Changes.pdf
Allan Cole - Timura Trilogy 01 - When the Gods Slept.pdf
should be placed in the following folders
应该放在以下文件夹中
/books/A/Allan Cole/Allan Cole - Timura Trilogy 01 - When the Gods Slept.pdf
/books/A/Andrew Weiner/Andrew Weiner - Changes.pdf
I need help with how to put this all into a bash script that will grab the filenames of all the PDF files in the current directory, and then move the files to the proper directory, creating the directory if it doesn't already exist.
我需要关于如何将这一切放入一个 bash 脚本的帮助,该脚本将获取当前目录中所有 PDF 文件的文件名,然后将文件移动到正确的目录,如果该目录不存在则创建该目录。
采纳答案by chaos
for f in *.pdf; do
name=`echo "$f"|sed 's/ -.*//'`
letter=`echo "$name"|cut -c1`
dir="DestinationDirectory/$letter/$name"
mkdir -p "$dir"
mv "$f" "$dir"
done
回答by Aevum Decessus
Actually found a different way of doing it, just thought I'd post this for others to see/use if they would like.
实际上找到了一种不同的方法,只是想如果他们愿意,我会发布给其他人查看/使用。
#!/bin/bash
dir="/books"
if [[ `ls | grep -c pdf` == 0 ]]
then
echo "NO PDF FILES"
else
for src in *.pdf
do
author=${src%%-*}
authorlength=$((${#author}-1))
letter=${author:0:1}
author=${author:0:$authorlength}
mkdir -p "$dir/$letter/$author"
mv -u "$src" "$dir/$letter/$author"
done
fi
回答by ghostdog74
@OP you can do it with just bash
@OP 你可以只用 bash 来做
dest="/tmp"
OFS=$IFS
IFS="-"
for f in *.pdf
do
base=${f%.pdf}
letter=${base:0:1}
set -- $base
fullname=
pdfname=
directory="$dest/$letter/$fullname"
mkdir -p $directory
cp "$f" $directory
done
IFS=$OFS
回答by Idelic
for i in *.pdf; do
dir=$(echo "$i" | \
sed 's/\(.\)\([^ ]\+\) \([^ ]\+\) - \(.*\)\.pdf/\/ /')
dir="DestinationDirectory/$dir"
mkdir -p -- "$dir" && mv -uv "$i" "$dir/$i"
done

