如何仅显示指定两个月份修改或创建的文件?无需grep且支持切换月份
Got it, let's work through your two file filtering requirements without relying on grep, and make sure switching month combinations is a breeze. Here's how to handle each case:
The find command is perfect here because it can directly evaluate file modification timestamps with human-readable date inputs—no grep needed. We'll use variables to define your target months so you can swap them out in seconds.
Example Command (GNU/Linux)
# Set your target months here (format: YYYY-MM) TARGET_MONTH1="2024-03" # March TARGET_MONTH2="2024-04" # April # Calculate the date range: start of first month, start of the month after the second START_DATE="${TARGET_MONTH1}-01" END_DATE=$(date -d "${TARGET_MONTH2}-01 +1 month" +%Y-%m-%d) # Find all files modified between START_DATE (inclusive) and END_DATE (exclusive) find /path/to/your/directory -type f -newermt "${START_DATE}" ! -newermt "${END_DATE}"
How to Switch Months
Just update TARGET_MONTH1 and TARGET_MONTH2—for example, change them to "2024-01" and "2024-03" to filter January and March modified files.
For macOS (BSD find/date)
BSD tools use slightly different syntax for date calculations. Replace the END_DATE line with this:
END_DATE=$(date -v+1m -j -f "%Y-%m-%d" "${TARGET_MONTH2}-01" +%Y-%m-%d)
This follows the same variable-driven pattern, but we'll target file creation timestamps instead of modification times.
Example Command (GNU/Linux)
# Set your target creation months here CREATE_MONTH1="2024-01" # January CREATE_MONTH2="2024-02" # February # Calculate the creation date range CREATE_START="${CREATE_MONTH1}-01" CREATE_END=$(date -d "${CREATE_MONTH2}-01 +1 month" +%Y-%m-%d) # Find all files created in the target months find /path/to/your/directory -type f -newerct "${CREATE_START}" ! -newerct "${CREATE_END}"
For macOS (BSD find)
BSD find uses the -B flag to target birth (creation) time. Adjust the find command to:
find /path/to/your/directory -type f -Bnewerct "${CREATE_START}" ! -Bnewerct "${CREATE_END}"
Bonus: Filter Any Year's Target Months
If you want to find files created in, say, January and February regardless of year, you can combine find with stat and awk (still no grep):
# Filter files created in Jan (01) or Feb (02), any year find /path/to/your/directory -type f -exec stat -c "%w %n" {} \; | awk '$1 ~ /^[0-9]{4}-(01|02)-/ {print $2}'
This works by printing each file's creation time and name, then using awk to match lines where the timestamp starts with a year followed by -01- or -02-, then outputting the filename.
内容的提问来源于stack exchange,提问作者Avoxy

