简体   繁体   中英

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.

#!/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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM