如何使用定义的变量创建带有子文件夹的文件夹?

如何使用定义的变量创建带有子文件夹的文件夹?

我有以下格式的文件:

2017-05-01-1500-00S.SRO___001_BH_Z
2017-05-01-1543-04S.SRO___001_BH_E
2017-05-01-1543-04S.SRO___001_BH_N
2017-05-01-1543-04S.SRO___001_BH_Z
2017-05-01-1600-00S.MOG___001_SP_E
2017-05-01-1600-00S.MOG___001_SP_N
2017-05-01-1600-00S.MOG___001_SP_Z
2017-05-01-1600-00S.MYA___001_SP_E
2017-05-01-1600-00S.MYA___001_SP_N
2017-05-01-1600-00S.MYA___001_SP_Z
2017-05-01-1600-00S.SRO___001_BH_E
2017-05-01-1600-00S.SRO___001_BH_N
2017-05-01-1600-00S.SRO___001_BH_Z

我编写了一个 bash 脚本,其中列出了一些变量:

英石 =ls -1 2* | awk -F "[.__]" '{print $2}' | sort | uniq

雜麻=ls -1 2* | awk -F "[__]" '{print $5$6}' |sort | uniq

=ls -1 2* | awk -F "-" '{print $3}' | sort | uniq

我想创建具有以下格式的文件夹:

st/ cmp/day

然后将相应的值复制到其文件夹中。

例如文件如下所列

2017-05-01-1500-00S.SRO___001_BH_Z
2017-05-01-1543-04S.SRO___001_BH_E
2017-05-01-1543-04S.SRO___001_BH_N
2017-05-01-1543-04S.SRO___001_BH_Z

st=SROcmp=BHZcmp=BHEcmp=BHN, 和day=01

所以我需要创建以下目录:

第一的SRO/BHE/01

第二SRO/BHN/01

第三SRO/BHZ/01

然后复制包含圣罗巴拿马式热电偶01(即day值)到其对应的目录。

我希望我已经提到了细节。

非常感谢。

答案1

因此,您有一个给定目录中的文件列表,就像问题中的文件列表一样。您想根据这些文件名的某些部分创建目录,然后将这些文件移动到相应的目录中,对吗?

如果是的话,这样怎么样?

#!/bin/bash

# Get the list of states(?)
st=$(ls -1 2* | awk -F "[._]" '{print $2}')

# Get the list of comparisons(?)
cmp=$(ls -1 2* | awk -F_ '{print $5$6}')

# Get the day
day=$(ls -1 2* | awk -F- '{print $3}')

# Loop over all of the states(?)
for i in ${st}; do

    # Loop over all of the comparisons(?)
    for j in ${cmp}; do

        # Break te comparisons into 2 fields.  The filenames
        # have an underscore between the two fields.  The mv
        # command fails if that underscore is not included.
        cmp1=$(echo ${j} | cut -c1,2)
        cmp2=$(echo ${j} | cut -c3)

        # Loop over the days
        for k in ${day}; do
            # echo "${i}/${j}/${k}"

            # Define the sub-directory, and make it.
            sd="./${i}/${j}/${k}"
            mkdir -p "${sd}"

            # Move all files found into the appropriate sub-directory
            # Ignore any error messages since some of the string
            # combinations do not exists as files.
            mv -v 2*${k}*${i}*${cmp1}_${cmp2}* ${sd} 2>/dev/null
        done
    done
done

exit 0

相关内容