我希望将文件(
abc1_gff
、abc2_gff
等)从当前目录 (cds.gff
) 移动到与其名称末尾的“abc#
”相匹配的新的、预先存在的文件夹 (example_name_abc1
、example_name_abc2
等)。这是一个视觉效果:
[Linux@vaughan test]$ tree
.
├── cds.gff
│ ├── abc1_cds
│ ├── abc1_cds.gff
│ ├── abc2_cds
│ ├── abc2_cds.gff
│ └── abc_cds
├── example_name_abc1
│ └── distraction_abc1.txt
├── example_name_abc2
│ └── abc2_distraction_abc2.txt
└── move_files.sh
我希望将
abc1_cds.gff
移至 example_name_abc1
,并将 abc2_cds.gff
移至 example_name_abc2
,无需任何其他更改。我这里有脚本move_files.sh
:
#!/bin/bash
# Iterate over files in the "cds.gff" directory
for file in cds.gff/*.gff; do
# Extract the filename without the path
filename="${file##*/}"
# Extract the last part of the folder name
last_part_of_folder="${filename%_cds.gff}"
# Check if there's a matching folder in the current directory
if [ -d "$last_part_of_folder" ]; then
# Move the file to the matching folder
mv "$file" "$last_part_of_folder/"
fi
done
运行后不会对任何文件位置产生任何更改
./move_files.sh
(并且它是可执行的)。有任何想法欢迎
这条线并没有达到你的预期:
if [ -d "$last_part_of_folder" ]; then
如果测试
$last_part_of_folder
中是否存在具有字面名称的目录;例如,是否存在名为 abc1
的目录。您需要在其前面加上通配符:
if [ -d *_"$last_part_of_folder" ]; then
如果两个(或更多)目录有可能具有相同的最右边子字符串,这当然是有风险的。您还需要对
mv
命令进行相同的更改。在启用跟踪的情况下运行此类脚本通常很有帮助:bash -x path-to-script
。