根据文件名中包含的日期查找文件

根据文件名中包含的日期查找文件

在下面的脚本中,我要求用户输入日期范围并应用该范围来过滤命令的结果find。该命令适用于名称包含日期的日志文件,如filename-YYYYMMDD.gz.一旦识别出此类文件,就会将其复制到新目录中。

到目前为止,我所拥有的(例如日期范围之类的)-newermt 20190820 ! -newermt 20190826不会在 25 日或 26 日复制文件。

更新:

#!/bin/bash




#Take input from user

read -p "Enter year (YYYY): " Y
read -p "Enter start month: " SM
read -p "Enter start day: " SD
read -p "Enter end month: " EM
read -p "Enter end day: " ED
read -p "Enter copy destination directory (with absolute path): " new_directory

# pad month and day numbers with zero to make the string 2 character long
SD="$(printf '%02d' $SD)"
SM="$(printf '%02d' $SM)"
ED="$(printf '%02d' $ED)"
EM="$(printf '%02d' $EM)"

# Make sure that the new directory exists
#mkdir -p new_directory

# Place the result of your filtered `find` in an array,
# but, before, make sure you set:
#IFS='\n'  # in case some file name stored in the array contains a space

array=(
        $(find /directory/log/ -name "test.file-*.gz" -execdir bash -c '
            filedate="$(basename ${0#./test.file-} .gz)";
            if [[ $filedate -gt $Y$SM$SD ]] && [[ $filedate -lt $Y$EM$ED ]]; then
                basename $0
            fi' {} \;
         )
      )

# loop over array, to copy selected files to destination directory

for i in "${array[@]}"; do
    # ensure that destination directory has full path
    cp "$i" "$new_directory"
done

我知道 find -newermt 命令正在查找在给定日期修改的文件而不是文件名。如果您知道有更好的方法,我将非常感激。

答案1

根据文件名中包含的日期查找文件

如果你的意思是真的 要过滤文件名中的日期,那么您可以执行以下操作:

#!/bin/bash

read -p "Enter year (YYYY): " Y
read -p "Enter start month number: " SM
read -p "Enter start day number: " SD
read -p "Enter end month number: " EM
read -p "Enter end day number: " ED
read -p "Enter copy destination directory (with absolute path): " new_directory

# Do some rule-based checking here. I.e. input variables above
# should conform to expected formats...

# pad month and day numbers with zero to make the string 2 character long
SD="$(printf '%02d' $SD)"
SM="$(printf '%02d' $SM)"
ED="$(printf '%02d' $ED)"
EM="$(printf '%02d' $EM)"

# Make sure that the new directory exists
mkdir -p "$new_directory"

# Place the result of your filtered `find` in an array,
# but, before, make sure you set:
IFS=$'\n'  # in case some file name stored in the array contains a space
sdate="$Y$SM$SD"
edate="$Y$EM$ED"

array=( 
        $(find /directory/log -name "filename-*.gz" -execdir  bash -c '
            filedate="$(basename ${0#./filename-} .gz)";
            if (("${filedate:-0}" >= "${1:-0}")) && 
               (("${filedate:-0}" <= "${2:-0}")); then
                echo "$0"
            fi' {} "$sdate" "$edate" \;) 
      )

# loop over array, to copy selected files to destination directory
#for i in "${array[@]}"; do
#    # ensure that destination directory has full path
#    cp "$i" "$new_directory"
#done

# ... or much cheaper than a loop, if you only need to copy...
cp "${array[@]}" "$new_directory"

相关内容