Home > database >  How do you create directories based on filenames and move identically-named files (different formats
How do you create directories based on filenames and move identically-named files (different formats

Time:11-25

I have a list of files in different formats, all named identically (i.e., file1.txt, file1.conf, file2.txt, file2.conf, etc.) in the same directory. What I'm trying to do is create directories based on the filename and then move all of the corresponding files into that newly-created directory.

I found several tangentially-related questions across Stack Overflow that I tried to bring together:

#!/bin/bash
for f in ./*.txt ./*.conf ; do
  [[ -e "$f" ]] 
  dir="${f%.*}"
  if [ ! -d "$dir" ] ; then
  mkdir "$dir"
  fi
  mv "$f".* "$dir"

done

I admittedly am brand new to working in the shell, so I don't fully understand the parameterization yet. I think in a for loop I'd use the -e flag to check that a .txt or .conf file exists, the filename gets assigned to $f, creates a directory named $f it doesn't already exist, and after that moves all files named $f with any sort of extension into the directory.

CodePudding user response:

Something like this I think.

#!/bin/sh

for file in ./*.txt ./*.conf; do
    basename="${file##*/}" # Remove the path e.g. ./file.txt ==> file.txt
    targetDir="${basename%.*}" # Remove the extension e.g. file.txt ==> file
    mkdir -p "$targetDir" # Create a new directory if not exist. Ignore otherwise.
    echo mv "$file" "$targetDir" # Move file to the target directory.
done

To do the job, remove the last echo.

  • Related