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

时间:2023-02-06 10:51:17

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.

任何帮助,将不胜感激。谢谢。

1 个解决方案

#1


1  

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

#1


1  

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