4

I apologize in advance if I am posting this in the wrong location, I am very new to scripting let alone stackoverflow:

I have a number of files ending in .conf in the same directory as a number of folders with the same names without the .conf extension. For example, my directory looks like this:

136
136.conf
139
139.conf
...

I would like to move the .conf files into their corresponding folder with a loop. I thought I could do this:

for f in *.conf; do
    dir=${f:0:13}
    mv "$f" "$dir"
done

but I am obviously doing something incorrectly. I would greatly appreciate anyone's help with this.

codeforester
  • 39,467
  • 16
  • 112
  • 140
foolsparadise
  • 43
  • 1
  • 3

1 Answers1

5

Use Bash parameter expansion to derive the directory name by removing the extension (anything that follows the .):

for f in *.conf; do
  [[ -f "$f" ]] || continue # skip if not regular file
  dir="${f%.*}"
  mv "$f" "$dir"
done

This is a little better than the substring approach since we make no assumption on the length of the filename or directory name.

codeforester
  • 39,467
  • 16
  • 112
  • 140