scripting_newbie
scripting_newbie

Reputation: 55

Linux - Create sub-directories from file names in current directory

I have a list of files in a directory like below.

/file1 - filename1.txt
/file2 - filename2a.txt
/file2 - filename2b.txt
/file3 - filename3.txt
/file4 - filename4.txt
/file5 - filename5.txt

I am trying to create a script that will parse the files in the specified or working directory, to create folders from the filenames before the dash, if they dont already exist and ignore that file if they do. Then the script will move that filename in the newly created sub-directory.

For example, the list will eventually look like the below.

/file1/file1 - filename1.txt
/file2/file2 - filename2a.txt
/file2/file2 - filename2b.txt
/file3/file3 - filename3.txt
/file4/file4 - filename4.txt
/file5/file5 - filename5.txt

Any help would be appreciated. Thank you.

Upvotes: 1

Views: 2440

Answers (1)

suspectus
suspectus

Reputation: 17258

#!/bin/bash
for f in filename*
do
   d=$( echo $f | sed 's/filename\([0-9]*\).*/file\1/')
   [ -d $d ] || mkdir $d
   mv $f $d
   echo "$f moved to $d"
done

Upvotes: 1

Related Questions