bash,列出文件名,数组

bash, list filenames, array

我有一个像

这样的目录结构
$ 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

像年一样的目录,每年有几个月的目录,里面是.nc文件。

我想要做的是获取提供的文件名数组开始和结束 years/months。

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

所以,我只想获取从 2011/03 年到 2013/08 年的所有文件名的数组,而无需进入目录。

有什么bash技巧吗?

试试这个:

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
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[@]}"