Linux
根據文件名中包含的日期查找文件
在下面的腳本中,我要求使用者輸入日期範圍並應用該範圍來過濾
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 命令正在查找在給定日期修改的文件,而不是文件名。如果您知道任何更好的方法,我將不勝感激。
根據文件名中包含的日期查找文件
如果你的意思是過濾 文件名中的日期,那麼你可以這樣做:
#!/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"