如果声明要查看文件

时间:2013-09-13 15:44:58

标签: bash

#!/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:无效选项 cd:用法:cd [-L | [-P [-e]]] [dir] mv:无效选项 - '9' 请尝试使用`mv --help'获取更多信息。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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