[英]How can i move/group specific folders in bash?
I have a folder structure like the following:我的文件夹结构如下:
2020-123-1
2020-123-2
2020-123-3
2020-124-1
2020-124-2
...
I need to create folders from the first 2 numbers and omit whatever follows the second dash (-).我需要从前 2 个数字创建文件夹,并省略第二个破折号 (-) 后面的任何内容。 Then I need to put the prior folders under the newly created ones with the correct name.然后我需要将以前的文件夹放在新创建的文件夹下,并使用正确的名称。
2020-123
->2020-123-1
->2020-123-2
->2020-123-3
2020-124
->2020-124-1
->2020-124-2
I tried to write a script in bash like this:我尝试在 bash 中编写一个脚本,如下所示:
ls -d */ > folder.txt
cut -f1,2 -d"-" folder.txt |cut -f1 -d"/" |sort|uniq > mainfolder.txt
while read line; do mkdir $line ; done < mainfolder.txt
while read line; do mv $(cut -f1,2 -d"-" $line) $line/ ; done < folder.txt
I couldn't make the last line work, I know it has issues.我无法使最后一行工作,我知道它有问题。
Actually, you don't have to parse the directory names and build the hierarchy.实际上,您不必解析目录名称并构建层次结构。 You can make use of the -p
option of mkdir
, thus, an awk one-liner will do the job:您可以使用mkdir
的-p
选项,因此,awk 单线将完成这项工作:
awk -F'-' '{top=$1 FS $2;printf "mkdir -p %s; mv %s %s\n",top, $0, top}' dir.txt
The output with your example: output 与您的示例:
mkdir -p 2020-123; mv 2020-123-1 2020-123
mkdir -p 2020-123; mv 2020-123-2 2020-123
mkdir -p 2020-123; mv 2020-123-3 2020-123
mkdir -p 2020-124; mv 2020-124-1 2020-124
mkdir -p 2020-124; mv 2020-124-2 2020-124
|sh
if everything looks fine.这个单行只打印命令而不执行它们,如果一切看起来都很好,你只需 pipe 和 output 到|sh
。 Examine the output commands, change the printf
format/values for adjustment.检查 output 命令,更改printf
格式/值以进行调整。So the final script is as follows:所以最终的脚本如下:
ls -d */ | cut -f1 -d"/" > folder.txt
awk -F'-' '{top=$1 FS $2;printf "mkdir -p %s; mv %s %s\n",top, $0, top}' folder.txt |sh
In pure bash:在纯 bash 中:
#!/bin/bash
for src in *-*-*; do
destdir=${src%-*}
[[ -d $destdir ]] || mkdir "$destdir" || exit
# This just prints out the command that will be called.
# Remove the "echo" in actual script after making sure it will run as intented
echo mv "$src" "$destdir"
done
In the script above it is assumed that each file name to be moved contains exactly two dashes.在上面的脚本中,假设要移动的每个文件名恰好包含两个破折号。 If it can contain two or more dashes then the destdir=${src%-*}
line should be replaced with these two lines:如果它可以包含两个或多个破折号,则destdir=${src%-*}
行应替换为以下两行:
suffix=${src#*-*-}
destdir=${src%"-$suffix"}
For detailed information read the "shell parameter expansion" section in bash reference .有关详细信息,请阅读bash 参考中的“shell 参数扩展”部分。
Additionally, a good read article is: Why you shouldn't parse the output of ls此外,一篇不错的阅读文章是: Why you should parse the output of ls
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.