简体   繁体   English

Bash:根据文件名对文件进行排序

[英]Bash: sorting files according to their name

I have a workdir filled with many *.dlg text files.我有一个工作目录,里面装满了许多 *.dlg 文本文件。 The name of each file is given in the following format每个文件的名称按以下格式给出

7000_01_lig_cne_1000.dlg
1300_01_lig_cne_1000.dlg
5000_01_lig_cne_1000.dlg
6000_01_lig_cne_1000.dlg

I need to write some bash workflow to sort these filles accoridng to its first index (a number occured at the begining of the name, before the first _): 1300, 7000, 5000 or 6000, and create separate directory for each of the index and then copy it into it.我需要编写一些 bash 工作流程来根据其第一个索引对这些填充进行排序(一个数字出现在名称的开头,在第一个 _ 之前):1300、7000、5000 或 6000,并为每个索引创建单独的目录然后复制进去。 In this example I should have 4 different directories: 7000, 1300, 5000 and 6000 with one file into it.在这个例子中,我应该有 4 个不同的目录:7000、1300、5000 和 6000,其中有一个文件。 But then I will have to apply the script for huge filles with the naming different after the first _但随后我将不得不将脚本应用于巨大的填充,在第一个 _ 之后命名不同

It may be something like this它可能是这样的

#!/bin/bash
#set the name of folder with folles to be sorted
FILES=$PWD/test
# where output directories should be created
OUTPUT=$PWD
for i in ${FILES}/[0-9]*_*.dlg      
do 
    mkdir -p  ${OUTPUT}/${i%%_*}       
    cp $i ${OUTPUT}/${i%%_*}
done

Here's one that copies files from current working dir and makes the new dirs in the same place:这是从当前工作目录复制文件并将新目录放在同一位置的一个:

for i in [0-9]*_*.dlg        # define this better to suit your needs
do 
    mkdir -p  ${i%%_*}       # remove substring starting from the 1st _
    cp $i ${i%%_*}
done

If the files are in a separate dir:如果文件位于单独的目录中:

for i in dir/[0-9]*_*dlg     # they are in dir or path
do 
    j=${i##*/}               # strip the path off from beginning to last /
    mkdir -p ${j%%_*}        # strip off from the first _ to the end
    cp $i ${j%%_*}
done

It will make dirs to current working directory.它将使目录指向当前工作目录。

Use quotes around variables if needed.如果需要,在变量周围使用引号。

Seems you want to arrange files via keywords, from your example:从您的示例中,您似乎想通过关键字排列文件:

mkdir 1300
cp 1300_01_lig_cne_1000.dlg 1300
mkdir 5000
cp 5000_01_lig_cne_1000.dlg 5000
mkdir 6000
cp 6000_01_lig_cne_1000.dlg 6000
mkdir 7000
cp 7000_01_lig_cne_1000.dlg 7000

If that is true, try below:如果这是真的,请尝试以下操作:

flist=()
for i in `ls`;
do
#folder name check
fname=`echo $i | cut -d '_' -f1;`
#if the file match no folder, create it
if [[ ! " ${flist[@]} " =~ " ${fname} " ]]; then
flist+=($fname)
echo "mkdir $fname" #do not remove echo unless you are sure
fi    
# if the file match the folder, copy or move it
if [[ " ${flist[@]} " =~ " ${fname} " ]]; then
echo "cp $i $fname" #do not remove echo unless you are sure
fi
done

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM