我的主目录中有几个文件,例如Apple-AP01
、Apple-AP02
、Banana-AP05
和Chocolate-RS33
其他文件,这些文件是从 ftp 服务器中提取的。在同一主目录中,有Fruit
、Sweet
等文件夹。在这些文件夹中,还有名称为Apple-AP01
、Apple-AP02
、Chocolate-RS33
等的子文件夹。
我需要在我的主目录上运行一个脚本,这样一旦我有了Apple-AP01
,它就知道根据“ AP
”关键字将其放入 Fruit 文件夹中,然后进一步将其放入该Apple-AP01
文件夹中。对于Chocolate-RS33
,则需要Sweet
根据“ RS
”关键字进入文件夹,然后进一步进入文件夹Chocolate-RS33
内的子文件夹Sweet
。我的所有文件都需要这个。有人可以写一个可以工作的 bash 脚本吗?
我试过了
for f in *.
do
name=`echo "$f"|sed 's/ -.*//'`
letter=`echo "$name"|cut -c1`
dir="DestinationDirectory/$letter/$name"
mkdir -p "$dir"
mv "$f" "$dir"
done
我想我需要使用for
循环,但我不知道如何在 bash 中做到这一点。
答案1
这应该涵盖您想做的大部分事情。
sortfood.sh
#!/bin/bash
# Puts files into subdirectories named after themselves in a directory.
# add more loops for more ID-criteria
for f in *AP*; do
mkdir -p "./fruit/$f";
mv -vn "$f" "./fruit/$f/";
done
for f in *RS*; do
mkdir -p "./sweet/$f";
mv -vn "$f" "./sweet/$f/";
done
答案2
检查一下,它是否满足您的要求。
第一种方式:
#!/bin/bash
declare -A arr_map
arr_map=([AP]=Fruit [RS]=Sweet)
# Iterate through indexes of array
for keyword in "${!arr_map[@]}"; do
# Search files containing the "-$keyword" pattern in the name
# like "-RS" or "-AP". This pattern can be tuned to the better matching.
for filename in *-"$keyword"*; do
# if file exists and it is regular file
if [ -f "$filename" ]; then
destination=${arr_map["$keyword"]}/"$filename"
# Remove these echo commands, after checking resulting commands.
echo mkdir -p "$destination"
echo mv -iv "$filename" "$destination"
fi
done
done
第二种方式:
#!/bin/bash
declare -A arr_map
arr_map=([AP]=Fruit [RS]=Sweet)
# Iterate through all files at once
for i in *; do
# If the file is a regular and its name conforms to the pattern
if [[ -f "$i" && "$i" =~ [A-Za-z]+-[A-Z]+[0-9]+ ]]; then
# trim all characters before the dash: '-' from the beginning
keyword=${i#*-}
# trim all digits from the ending
keyword=${keyword%%[0-9]*}
# if the arr_map contains this keyword
if [[ ${arr_map["$keyword"]} != "" ]]; then
destination=${arr_map["$keyword"]}/$i
# Remove these echo commands, after checking resulting commands.
echo mkdir -p "$destination"
echo mv -iv "$i" "$destination"
fi
fi
done