[英]Find pattern of the file, create a folder with that pattern and copy the files to that folder - Bash script
I have a task, to find the pattern of the file, create a folder with the pattern name and copy the file to that folder. 我有一个任务,要查找文件的模式,使用模式名称创建一个文件夹,然后将文件复制到该文件夹。 I am able to create the folders.
我能够创建文件夹。
folders=`find /Location -type f -name "*.pdf" -printf "%f\n" | cut -f 1 -d '_' | sort -u`
for i in $folders
do
mkdir -p /LocationToCreateTheFolder/$i
done
Not able to go further on how to copy the files. 无法进一步说明如何复制文件。
也许尝试?
for i in $folders do mkdir -p /LocationToCreateTheFolder/$i && cp ./$i.pdf ./$i/
This will do the finding and the copying: 这将进行查找和复制:
find Location -type f -name '*.pdf' -exec bash -c 'f=${1##*/}; d="LocationToCreateTheFolder/${f%%_*}"; mkdir -p "$d" && cp "$1" "$d"' None {} \;
This is safe for difficult file names even ones that contain spaces, tabs, or newlines in their names. 这对于困难的文件名是安全的,即使文件名中包含空格,制表符或换行符也是如此。
find Location -type f -name '*.pdf' -exec bash -c '...'
None {} \\; find Location -type f -name '*.pdf' -exec bash -c '...'
None {} \\;
This will find the pdf files under directory Location
and, for each one found, the bash commands inside '...'
will be executed with $1
set to the name of the file found. 这将在目录
Location
下找到pdf文件,对于找到的每个pdf文件,将在$1
设置为找到的文件名的情况下执行'...'
的bash命令。 ( $0
is set to None
. We don't use $0
.) (
$0
设置为None
。我们不使用$0
)
f=${1##*/}
This removes the directory names from the name of the file. 这将从文件名中删除目录名。 This is an example of prefix removal : everything in
$1
up to and including the last /
is removed. 这是一个删除前缀的示例:
$1
之前的所有内容(包括最后一个/
都将被删除。
d="LocationToCreateTheFolder/${f%%_*}"
This creates the name of the directory to which we want to send the file. 这将创建我们要将文件发送到的目录的名称。
${f%%_*}"
is an example of suffix removal . Everything in $f
from the first _
and after is removed. ${f%%_*}"
是删除后缀的示例。 $f
中第一个_
和之后的所有内容都将被删除。
mkdir -p "$d" && cp "$1" "$d"
This makes sure that the directory exists and then copies the file to it. 这样可以确保该目录存在,然后将文件复制到该目录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.