Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash move file to folder of same name [duplicate]

Tags:

bash

rename

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.

like image 379
foolsparadise Avatar asked Nov 15 '25 17:11

foolsparadise


1 Answers

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.

like image 86
codeforester Avatar answered Nov 17 '25 08:11

codeforester



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!