从文件名创建目录并移动 bash
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/13020720/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
creating directory from filename and move bash
提问by alexd106
I have a load of files
我有很多文件
BR0200.aaa.tsv
BR0200.bbb.tsv
BR0200.ccc.tsv
BR0210.aaa.tsv
BR0210.bbb.tsv
BR0210.ccc.tsv
W0210.aaa.tsv
W0210.aaa.tsv
W0210.aaa.tsv
I would like to create a series of directories based on the first part of the filename up to the first '.'
我想根据文件名的第一部分到第一个 '.' 创建一系列目录。
BR0200
BR210
W0210
and then move the associated files to the correct directories (i.e. all BR0200.* files to BR0200 directory).
然后将关联的文件移动到正确的目录(即所有 BR0200.* 文件到 BR0200 目录)。
I have had a stab at a bash script but I keep getting errors. Any advice would be gratefully received.
我曾尝试过 bash 脚本,但我不断收到错误消息。任何建议将不胜感激。
#!/bin/bash
for file in BR* W0*; do
dir = "${file%%.*}"
if [-e $dir];then
mv "$file" "$dir"
else
mkdir -p "$dir"
mv "$file" "$dir"
fi
done
Sorry if this is a basic question. I have tried searching the web, but with no result.
对不起,如果这是一个基本问题。我试过在网上搜索,但没有结果。
采纳答案by John Kugelman
There's no whitespace allowed around the =in an assignment.
=作业中的周围不允许有空格。
dir="${file%%.*}"
Conversely, whitespace is requiredin a test.
相反,测试中需要空格。
if [ -e $dir ]; then
    ^       ^
As far as stylistic improvements, it doesn't hurt to do an unnecessary mkdir -p, so you can get rid of the ifstatement.
就风格改进而言,做一个不必要的 没有什么坏处mkdir -p,所以你可以摆脱if声明。
Quotes aren't required in an assignment, so you can remove them from the dir=line. Quoting is a good idea everywhere else though, so don't delete the other quotes.
作业中不需要引号,因此您可以将它们从dir=行中删除。不过,在其他任何地方引用都是一个好主意,所以不要删除其他引用。
It might be good to add an extra .*to the for loop. That way if you run the script more than once it won't try to move those newly-created sub-directories. And a neat trick (though not necessarily an improvement) is to shorten BR*.* W0*.*to {BR,W0}*.*.
.*向 for 循环添加额外的内容可能会很好。这样,如果您多次运行脚本,它就不会尝试移动那些新创建的子目录。一个巧妙的技巧(虽然不一定是改进)是缩短BR*.* W0*.*到{BR,W0}*.*.
for file in {BR,W0}*.*; do
    dir=${file%%.*}
    mkdir -p "$dir"
    mv "$file" "$dir"
done
回答by Joana Carvalho
You can try something like this:
你可以尝试这样的事情:
for file in BR* WO*
do
dir=$(echo ${file} | awk -F. '{print }' OFS=.)
mkdir $dir
mv $file $dir
done
I had a similar situation and this worked for me.
我有类似的情况,这对我有用。

