首页 > 解决方案 > 将文件夹移动到unix中按字母顺序排列的子目录

问题描述

给定一个公司名称文件夹:

Ace inc
Austerity
A to Z
Beeline Industries
Bing
Booze inc.
Crypto
....
Zeebra 

...我需要将所有 A* 文件夹移动到子目录 A 中:

A/Ace inc
A/Austerity
A/A to Z
...

我尝试了以下命令:mv A* /A/它一直工作到一个点,然后失败,因为它试图将新创建的移动A/到自身中。

此外-我觉得已经运行过一次这个命令,我可能把我们的文件系统弄得一团糟。

标签: linuxunixsubdirectorymv

解决方案


您想在开始移动之前创建文件名列表。除非您以SuperUser/...的身份运行,否则您不应该能够写入,因此您不应该破坏任何东西(您很可能把包含原始文件的子目录弄得一团糟......)root

要创建当前目录中的文件列表并逐个遍历它们,您可以简单地使用for fname in *; do ... done. 您将需要引用所有后续用法fname以防止分词。由于您还标记了您的 questionshell而不是bash等,您将需要使用符合 POSIX 的方式来获取fc每个文件名的第一个字符 ( )。为此,您可以expr substr "$fname" 1 1在命令替换中使用旧的,例如

    fc=$(expr substr "$fname" 1 1)  ## use 'expr substr ...' to get 1st char

将它完全放在一个符合 POSIX 的 shell 脚本中,该脚本只对当前目录中的文件进行操作,根据文件名的第一个字符将当前目录中的所有文件移动到适当的子目录中,您可以这样做:

#!/bin/sh

for fname in *; do                  ## loop over each file
    [ -d "$fname" ] && continue     ## skip all directory names
    fc=$(expr substr "$fname" 1 1)  ## use 'expr substr ...' to get 1st char
    mkdir -p "$fc" || exit 1        ## create the directory or exit
    mv "$fname" "$fc" || exit 1     ## move the file or exit
done

产生的目录结构

使用您在示例列表中提供的文件名将导致以下目录结构:

$ tree .
.
├── A
│   ├── A to Z
│   ├── Ace inc
│   └── Austerity
├── B
│   ├── Beeline Industries
│   ├── Bing
│   └── Booze inc.
├── C
│   └── Crypto
└── Z
    └── Zeebra

如果您在修复文件系统方面需要帮助,您需要在其他 StackExchange 站点Super UserUnix & Linux上提出该问题,因为它与“编程”无关。

如果您有bash或其他一些支持字符串索引作为参数扩展的 shell,那么使用它来获取第一个字符会更快,并避免命令替换所需的子 shell$(expr ...)

如果您对将文件移动到子目录还有其他问题,请告诉我。

编辑基于澄清不移动当前目录中的文件

好的,如果我们已经了解(1)您正在bash作为您的 shell 运行,(2)您不想移动当前目录中的文件,子目录下,以及(3)只想移动包含在工作目录中的目录从目录名称的第一个字符创建的目录下面的目录(及其内容),您可以在下面进行以下更改:

#!/bin/bash

for fname in *; do                  ## loop over each file
    [ -f "$fname" ] && continue     ## skip files in the current dir
    fc=${fname:0:1}                 ## use parameter expansion for 1st char
    mkdir -p "$fc" || exit 1        ## create the directory or exit
    [ "$fc" = "$fname" ] && continue    ## don't move dir into itself
    mv "$fname" "$fc" || exit 1     ## move the directory or exit
done

原始目录结构

您的脚本在当前目录和其他目录中的示例,Apples其中Cans包含需要分别移动到'A''C'目录下的文件:

$ tree .
.
├── A
│   ├── A to Z
│   ├── Ace inc
│   └── Austerity
├── Apples
│   ├── file1
│   └── file2.3
├── B
│   ├── Beeline Industries
│   ├── Bing
│   └── Booze inc.
├── C
│   └── Crypto
├── Cans
│   ├── file1
│   ├── file2
│   └── file3
├── Z
│   └── Zeebra
└── script.sh

示例使用

$ bash script.sh

产生的目录结构

$ tree .
.
├── A
│   ├── A to Z
│   ├── Ace inc
│   ├── Apples
│   │   ├── file1
│   │   └── file2.3
│   └── Austerity
├── B
│   ├── Beeline Industries
│   ├── Bing
│   └── Booze inc.
├── C
│   ├── Cans
│   │   ├── file1
│   │   ├── file2
│   │   └── file3
│   └── Crypto
├── Z
│   └── Zeebra
└── script.sh

看看这个,让我知道我们是否就您需要完成的工作进行了一次会议。


推荐阅读