You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在命令行删除特定大小文件?现有命令执行异常求助

Fixing Accidental Deletion of All .gz Files When Targeting <2KB Ones

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/data if 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: k here means 1024 bytes; if you mean exactly 2000 bytes, use -size -2000c instead)
  • -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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:48:52