Ahmed Shokry
Ahmed Shokry

Reputation: 1

move files to new folders with the same name as the file?

How can I move a group of files that share the first 9 characters of the name of the files to created folders with the same name of 9 characters

 example

  I have a folder containing number of files with various names each
  group    of files begin with same 9 characters ex:

  first group [HD9523587_352, HD9523587_258, HD9523587_785 ,HD9523587_473]
  second group[Hip046329_258, Hip046329_364, Hip046329_681, Hip046329_235]

  and so on

I need to make new folders with the same 9 characters of the each group then move each group files into those folders. thanks

Upvotes: 0

Views: 1709

Answers (1)

chepner
chepner

Reputation: 532268

Just extract the first 9 characters to use as the directory name. In bash, the simplest way to do that is to use a regular expression match parameter substring expansion.

for f in *; do
    # [[ $f =~ ^(.{9}) ]]
    # dir=${BASH_REMATCH[1]}
    dir=${f:0:9}
    mkdir -p "$dir" && mv "$f" "$dir"
done

Upvotes: 8

Related Questions