Search code examples
fileunixdirectorysubdirectory

unix reorganize files into subdirectories based on name strings


I'm looking to move files (abc1_gff, abc2_gff, etc) from their current dir (cds.gff) to new, preexisting folders that match the "abc#" at the end of their names (example_name_abc1, example_name_abc2, etc). Here's a visual:

[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

Where I'd expect abc1_cds.gff to be moved into example_name_abc1, and abc2_cds.gff to be moved into example_name_abc2 with no additional changes. I have the script move_files.sh here:

#!/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

which yields no changes to any file locations after running ./move_files.sh (and it's executable). Any thoughts welcome


Solution

  • This line does not do what you seem to expect:

    if [ -d "$last_part_of_folder" ]; then
    

    If it testing if there is a directory with the literal name held in $last_part_of_folder; e.g., does a directory named abc1 exist. You need to preface it with a wildcard:

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

    This, of course is risky if there is any chance of two (or more) directories having the same rightmost substring. You also need to make the same change to the mv command. Running this type of script with tracing enabled is often helpful: bash -x path-to-script.