如何在命令行删除特定大小文件?现有命令执行异常求助
Hey Joe, sounds like your command's logic is tripping you up—let's get this sorted out. The issue almost certainly comes from miscombining file selection criteria, so let's break down the problem and fix it properly.
Common Mistake to Avoid
If you tried something like rm *.gz -size -2k, that's exactly why all .gz files got deleted: rm doesn't recognize the -size flag. It treats *.gz as the full list of files to delete, and -size as an invalid filename (you probably saw an error about that too). That command essentially tells rm to wipe every .gz file in the directory, ignoring the unrecognized flag entirely.
Correct Approach with find
The safest and most precise way to delete only .gz files smaller than 2KB is to use find with combined filters. Here's the right command:
find . -type f -name "*.gz" -size -2k -delete
Let's break down what each part does:
.: Starts searching from the current directory (replace with a specific path like/home/your/dataif you need to target a folder elsewhere)-type f: Ensures we only target regular files (not directories or symlinks)-name "*.gz": Filters to only files ending with.gz(the quotes prevent your shell from expanding the wildcard early, which can cause unexpected behavior)-size -2k: Selects files smaller than 2KB (note:khere means 1024 bytes; if you mean exactly 2000 bytes, use-size -2000cinstead)-delete: Deletes the matching files (always test first without this flag to verify the list of files to delete!)
Critical Testing Step
Before you run the command with -delete, run this first to check which files will be removed:
find . -type f -name "*.gz" -size -2k
Double-check that the output only includes the small .gz files you actually want to delete. Once you're confident, add the -delete flag.
Alternative: Using xargs (If Preferred)
If you want to use rm explicitly with find, you can pipe results to xargs—though -delete is simpler and more efficient. Here's how:
find . -type f -name "*.gz" -size -2k | xargs rm
Just make sure there are no filenames with spaces (if there are, add -print0 to find and -0 to xargs to handle them safely):
find . -type f -name "*.gz" -size -2k -print0 | xargs -0 rm
That should fix your problem—no more accidental mass deletions of .gz files!
内容的提问来源于stack exchange,提问作者Joe

