如何优化命令以按当前日期列出文件并仅输出文件名
Got it, let's fix this for you. The issue with your current commands is that ls -l outputs all the extra metadata you don't want, and plain ls doesn't show modification dates at all—so grep can't find the date to filter on. Here are two solid ways to get just the filenames you need:
Method 1: Use find (Most Reliable)
This is the best approach because it handles filenames with spaces or special characters correctly, and it’s built for exactly this kind of filtering. Run this command:
find /var/www/html/test -maxdepth 1 -type f -daystart -mtime 0 -printf "%f\n"
Let’s break down what each part does:
-maxdepth 1: Only look in the target directory, not subdirectories-type f: Only include files (exclude folders)-daystart: Calculate modification time starting from midnight today (instead of the last 24 hours)-mtime 0: Selects files modified within the current day (thanks to-daystart)-printf "%f\n": Prints just the filename (without the full path), one per line
Method 2: Use ls + awk (Simpler, but Watch for Spaces)
If you prefer sticking with ls, you can use awk to extract the last field (the filename) from the filtered ls -l output. Note this works best if your filenames don’t contain spaces:
ls -l /var/www/html/test --time-style=+%D | grep $(date +%D) | awk '{print $NF}'
$NFinawkrefers to the "number of fields"—so it grabs the last field in each line, which is your filename.
Why your previous ls without -l failed: Plain ls doesn’t display modification dates, so there’s nothing for grep $(date +%D) to match against. That’s why that command returned nothing useful.
内容的提问来源于stack exchange,提问作者jojo

