如何查找当前周内(不含当日、非过去7天)修改的文件?
Great question! Your existing -mtime +1 -mtime -7 command works for a rolling 7-day window, but to target only the current week (excluding today)—like Monday and Tuesday if today is Wednesday—we need to anchor our search to the start of the week instead of a fixed 7-day range.
Here's the Approach
We'll use GNU find's -newermt flag (which lets us specify exact date/time ranges) combined with date commands to calculate the start of the current week and the end of yesterday.
Step-by-Step Command
First, let's define our date boundaries:
- Start of the week: First day of the current week (we'll assume Monday as the start—adjust if your week starts on Sunday).
- End of the window: Last second of yesterday (to exclude any files modified today).
Run this command, replacing "name_pattern" with your actual file name pattern:
find . -name "name_pattern" \ -newermt "$(date -d "last monday" +%Y-%m-%d)" \ ! -newermt "$(date -d "yesterday" +%Y-%m-%d) 23:59:59"
Breakdown of Each Part
newermt "$(date -d "last monday" +%Y-%m-%d)": Matches files modified after the start of the current week (Monday 00:00:00).! -newermt "$(date -d "yesterday" +%Y-%m-%d) 23:59:59": Excludes files modified after the end of yesterday (so we only keep files from Monday through yesterday).
Adjustments for Different Week Starts
If your week starts on Sunday instead of Monday, just replace "last monday" with "last sunday":
find . -name "name_pattern" \ -newermt "$(date -d "last sunday" +%Y-%m-%d)" \ ! -newermt "$(date -d "yesterday" +%Y-%m-%d) 23:59:59"
Note for BSD/macOS Users
BSD find (used on macOS) doesn't support -newermt directly. Instead, use -newerct and adjust the date command syntax:
# For macOS (week starts on Monday) find . -name "name_pattern" \ -newerct "$(date -v -$(($(date +%u)-1))d +%Y-%m-%d)" \ ! -newerct "$(date -v -1d +%Y-%m-%d) 23:59:59"
The date -v -$(($(date +%u)-1))d part calculates the start of the current week (subtracts the number of days since Monday from today's date).
Edge Case: If Today is Monday
If today is Monday, this command will return no results—since the current week (starting Monday) only includes today, which we're excluding. That's expected behavior per your requirements!
内容的提问来源于stack exchange,提问作者Bogdan Dubyk

