linux - 将文件夹移动到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/
到自身中。
此外-我觉得已经运行过一次这个命令,我可能把我们的文件系统弄得一团糟。
解决方案
您想在开始移动之前创建文件名列表。除非您以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 User或Unix & 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
看看这个,让我知道我们是否就您需要完成的工作进行了一次会议。
推荐阅读
- c# - 从输入文件返回字符串
- ansible - Ansible 在块/救援失败的错误中调用 aws_s3 windows 主机,这很难理解
- c# - Azure 服务总线 C# 异常:无法连接到远程服务器
- php - mysql数据库读取通信包报错
- python-sphinx - 在 RTD 服务器上发布时使用 Plantuml
- rascal - 哪个替代方案是 ADT 的实例?
- regex - 我们可以在正则表达式模式中添加“
- image-processing - 各向异性扩散如何依赖于时间?
- mysql - 字段列表中的“SSN”列不明确
- javascript - 在 Eclipse 中,我在编写带有私有字段的类的 javascript 文件中出现错误