Unix 根据名称字符串将文件重新组织到子目录中

unix reorganize files into subdirectories based on name strings

提问人:Geomicro 提问时间:10/3/2023 更新时间:10/3/2023 访问量:23

问:

我希望将文件(、等)从当前目录()移动到新的、预先存在的文件夹,这些文件夹与其名称(、等)末尾的“”相匹配。下面是一个视觉对象:abc1_gffabc2_gffcds.gffabc#example_name_abc1example_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.gffexample_name_abc1abc2_cds.gffexample_name_abc2move_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

文件 UNIX 目录

评论


答:

1赞 Kurtis Rader 10/3/2023 #1

此行没有执行您似乎期望的操作:

if [ -d "$last_part_of_folder" ]; then

如果它测试是否存在一个包含文字名称的目录;例如,是否存在一个名为的目录。您需要在它前面加上一个通配符:$last_part_of_folderabc1

if [ -d *_"$last_part_of_folder" ]; then

当然,如果两个(或更多)目录有可能具有相同的最右边的子字符串,这当然是有风险的。您还需要对命令进行相同的更改。在启用跟踪的情况下运行此类脚本通常很有帮助:。mvbash -x path-to-script