简体   繁体   English

Linux-从当前目录中的文件名创建子目录

[英]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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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