Creating Directories

I have many pdf files with similar naming conventions as this one: AC41_AC85_86_AC128_129_MC171_173_SF_207_FMV.pdf. It is a pdf file containing evaluations for these locations: AC41, AC85, AC86, AC128, AC129, MC171, and MC173.

I want to create a directory for every location and put the associated pdf in that directory.

The final product I want is a directory named AC41 and to put the file AC41_AC85_86_AC128_129_MC171_173_SF_207_FMV.pdf into the directory. Next, a directory named AC85 and put the file into it. Also, continue to cycle through this pdf and all pdfs in the folder.

I have a script:

#!/bin/sh

set -e
for f in *.pdf
do 
d=${f%_*.*}
if [ ! -d "$d" ]; then
mkdir "$d"
fi 
mv -f "$f" "$d"
done

This only creates one directory per file. What am I missing?

Your variable subsitution removes the string "_FMV.pdf" from the end of $f and puts that into $d. However, the value of $d is then AC41_AC85_86_AC128_129_MC171_173_SF_207.

I'm surmising this is the name of the one directory that is getting created, and it moves the pdf file there, based upon your script.

You'll need to break out the values of $d in some way so that you can then create the appropriate individual directories AC41, AC85, etc. and place the file in each of them.

One caveat I see is that some of the numbers in the file name don't have the matching letter prefix to your location list. Like AC86, there is just an 86, so if you don't want a directory named simply '86' you'll need to handle this condition. Also, you don't list 'SF' or the '207' as locations and those values are still in $d after your substitution.

Assuming you've planned out your location anomalies, you can break out $d like this:

for drt in $(IFS=_;echo $d)
do
  if [ ! -d "$drt" ]; then
    mkdir "$drt"
  fi
  mv -f "$f" "$drt"
done

Thanks for the suggestion. It works for the first file, but does not continue to loop through the other files. The code now is:

#!/bin/sh

set -e
for f in .pdf
do
d=${f%_*.
}
done
for drt in $(IFS=_;echo $d)
do
if [ ! -d "$drt" ]; then
mkdir "$drt"
fi
cp -f "$f" "$drt"
done

You need to nest one for loop inside the other for loop.

Move the red "done" to where the blue "done" is as shown below,
and try that.

set -e
for f in *.pdf
do 
  d=${f%_*.*}
done # <---remove this
  for drt in $(IFS=_;echo $d)
  do
    if [ ! -d "$drt" ]; then
    mkdir "$drt"
    fi 
    cp -f "$f" "$drt"
  done
done # <--- add this