简体   繁体   English

bash,列出文件名,数组

[英]bash, list filenames, array

I have a dir structure like 我有一个目录结构

$ ls /comp/drive/
2009  2010  2011  2012  2013  2014

$ ls 2009
01  02  03  04  05  06  07  09  10  11  12

$ ls 2013
01  02  04  05  06  08  09  10  12

$ ls 2013/04/*.nc
file4.nc file44.nc file45.nc file49.nc

There are dirs like years and each year there are few months dirs and inside are .nc files. 有像几年这样的目录,每年有几个月目录,并且里面是.nc文件。

What I want to do is get the array of filenames provided start and end years/months. 我想做的是获取提供的文件名数组,这些文件名包含开始和结束的年/月。

eg sYear=2011; eYear=2013; sMonth=03; eMonth=08 例如sYear=2011; eYear=2013; sMonth=03; eMonth=08 sYear=2011; eYear=2013; sMonth=03; eMonth=08

So, I want to get the array of all filenames from year 2011/03 to 2013/08 only without going inside the dirs. 因此,我只想获取2011/03到2013/08年所有文件名的数组,而无需深入目录。

Any bash trick? 有什么b俩吗?

sYear=2011; eYear=2013; sMonth=03; eMonth=08

# prevent bugs from interpreting numbers as hex
sMonth=$(( 10#$sMonth ))
eMonth=$(( 10#$eMonth ))

files=( )
for (( curYear=sYear; curYear <= eYear; curYear++ )); do
  # include only months after sMonth
  for monthDir in "$curYear"/*/; do
    [[ -e $monthDir ]] || continue # ignore years that don't exist
    curMonth=${monthDir##*/}
    (( curMonth )) || continue     # ignore non-numeric directory names
    (( curYear == sYear )) && (( 10#$curMonth < sMonth )) && continue
    (( curYear == eYear )) && (( 10#$curMonth > eMonth )) && continue
    files+=( "$monthDir"/*.nc )
  done
done

printf '%q\n' "${files[@]}"

Try this: 尝试这个:

sYear=2011
sMonth=03

eYear=2013
eMonth=08

shopt -s nullglob
declare -a files

for year in *; do
    (( ${year} < ${sYear} || ${year} > ${eYear} )) && continue

    for year_month in ${year}/*; do

        month=${year_month##*/}
        (( ${year} == ${sYear} && ${month##0} < ${sMonth##0} )) && continue;
        (( ${year} == ${eYear} && ${month##0} > ${eMonth##0} )) && continue;

        files+=(${year_month}/*.nc)
    done
done

echo "${files[@]}"
# printf "$(pwd)/%q\n" "${files[@]}" # for full path

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

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