1
#!/bin/bash

# This would match files that begin with YYYYMMDD format.
files=(*[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9].wav)

# If you want to match those in the current year, start it with that year instead.
# current_year=$(date +%Y)
# files=("$current_year"[0-9][0-9][0-9][0-9]*)

#expands its values to multiple arguments '${files[@]}'
for file in ${files[@]}; do
file_date=${file:(-12):8}
file_year=${file_date:0:4}  
file_month=${file_date:4:2}

#  Adding -p option to mkdir would create the directory only if it doesn't exist.
  mkdir -p "$file_year"

  file_month=${file:4:2}
  cd  $file_year
  mkdir -p "$file_month"
  cd ..
  mv $files "$file_year"/"$file_month"

done

第 20 行出现错误: cd: -9: invalid option cd: usage: cd [-L|[-P [-e]]] [dir] mv: invalid option -- '9' Try `mv --help' for更多信息。

4

3 回答 3

0

我不是 bash 专家,但有几种方法可以做到这一点。

  • 您可以将其他案例合并到您的files匹配器中。
  • 您可以开发涵盖您想要的案例的其他匹配器,并依次检查每个匹配器

第二个伪代码:

# This would match files that begin with YYYYMMDD format.
files=([0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]*)

# This would match the "OUTXXX-" files (just conceptually, but you get the idea).
files_out=(OUT[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]*)

# etc.

# Now process each matched list in turn
于 2013-09-13T15:53:10.030 回答
0
#!/bin/bash

# When a match is not found, just present nothing.
shopt -s nullglob

# Match all .wav files containing the date format.
files=(*[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]*.wav)

if [[ ${#files[@]} -eq 0 ]]; then
    echo "No match found."
fi

for file in "${files[@]}"; do
    # We get the date part by part
    file_date=''
    # Split it into parts.
    IFS="-." read -ra parts <<< "$file"
    for t in "${parts[@]}"; do
            # Break from the loop if a match is found
        if [[ $t == [0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9] ]]; then
            file_date=$t
            break
        fi
    done
    # If a value was not assigned, then show an error message and continue to the next file.
    if [[ -z $file_date ]]; then
        echo "Unable to find date string in $file."
        continue
    fi

    file_year=${file_date:0:4}
    file_month=${file_date:4:2}

    mkdir -p "$file_year/$file_month"

    # -- is just there to not interpret filenames starting with - as options.
    echo mv -- "$file" "$file_year/$file_month"
done
于 2013-09-13T16:03:18.370 回答
0

在你编辑你的原始问题之前,你有一些像这样的文件名:OUTxxx - 20130913.wav. 根据此文件名,您可以执行以下操作。它也适用于文件名qxxxx - 20130913.wavxxxx- 20130913.wav.

IFS=$(echo -en "\n\b");
for file in $(find . -type f -name "*.wav"); 
do 
  fn=$(echo $file | sed -e 's/.*- //g' -e 's/\.wav//g');
  fyear=${fn:0:4};
  fmonth=${fn:4:2};
  fdate=${fn:6:2};
  echo $fyear; echo $fmonth;echo $fdate;
  mkdir -p "$fyear"/"$fmonth";
  mv $fn "$fyear"/"$fmonth";
done
于 2013-09-13T17:03:45.240 回答