remove-except
Have you ever wanted to keep only a few items among many files in a directory and remove everything else, including items in nested directories? I have. Of course, a script can do that. But I thought it would be more convenient to have a command that only requires the paths or patterns to keep. That is why I made remove-except.
remove-except keeps items selected by paths or glob patterns and modification times, and deletes the other items under the selected directory.
Safety Notice
This tool permanently deletes files and directories. Back up important data before running it. Before deleting anything, use --dry-run and review every item. --summary omits paths, so do not use it for the pre-deletion review. If nothing matches the keep conditions, everything under the selected directory becomes a deletion target. Especially when using --force, verify that the intended conditions match items. When passing patterns generated by another command with --patterns-from-stdin, also use --dry-run to verify that the generated patterns are what you intended. When using --root, verify that the displayed directory is the intended location. A filesystem's top-level directory cannot be selected for processing.
With modification-time filtering, even explicitly named links and empty directories may be deleted. If no file meets all keep conditions, everything becomes a deletion target.
Installation
Prebuilt Binaries
The v0.5.1 GitHub Release provides prebuilt binaries for Windows x64 and Linux x64. The older v0.2.4 release provides source code only.
Version v0.5.1 supports the modification-time options and JSON schema 2. They are not included in v0.4.0.
Download the archives and checksums from the GitHub Release Assets:
| Platform | Archive | SHA-256 file |
|---|---|---|
| Windows x64 (MSVC) | remove-except-v0.5.1-x86_64-pc-windows-msvc.zip |
remove-except-v0.5.1-x86_64-pc-windows-msvc.zip.sha256 |
| Linux x64 (GNU) | remove-except-v0.5.1-x86_64-unknown-linux-gnu.tar.gz |
remove-except-v0.5.1-x86_64-unknown-linux-gnu.tar.gz.sha256 |
The Linux binary is built in Ubuntu 22.04 and requires glibc 2.35 or later. Ubuntu is the supported Linux platform; the glibc requirement alone does not guarantee compatibility with other distributions. macOS, ARM64, and musl binaries are not included. Prebuilt binaries do not require a Rust toolchain.
Before extracting or running the binary, verify the archive's SHA-256. On Windows, compare the hash from Get-FileHash with the first field in the checksum file (case-insensitive); do not continue if they differ:
Get-FileHash .\remove-except-v0.5.1-x86_64-pc-windows-msvc.zip -Algorithm SHA256
Get-Content .\remove-except-v0.5.1-x86_64-pc-windows-msvc.zip.sha256
On Ubuntu, place the archive and checksum in the same directory and run:
Also verify the archive's GitHub Actions build provenance with GitHub CLI, replacing <archive-path> with the downloaded archive's path:
The attestation is registered with GitHub, not supplied as a separate Release asset. Binaries embed dependency crate names and versions using cargo-auditable; a separate SBOM file is not included. Neither embedded dependency data, a checksum, nor an attestation guarantees that a binary is safe.
After verification, extract the archive:
Expand-Archive -LiteralPath .\remove-except-v0.5.1-x86_64-pc-windows-msvc.zip -DestinationPath .\remove-except-v0.5.1
Each archive contains a platform-named directory with remove-except.exe (Windows) or remove-except (Ubuntu), both READMEs, and both project licenses. Add the directory containing the executable to PATH, then check remove-except --version.
Install from Source
Install Rust 1.88 or later, then install from the published v0.5.1 tag:
To install the development version, omit the tag and use the latest default-branch source. It may differ from the published v0.5.1 release:
You can also clone the repository and install from its top-level directory with cargo install --path . --locked. To install the older source-only release, use --tag v0.2.4 instead; it does not include stdin patterns, JSON output, exit codes 2 and 3, whole-line confirmation, the viewer, or the final-confirmation recap.
Install from crates.io
See the remove-except crates.io page for the latest published version and details. Install Rust 1.88 or later and run:
Quick Start
The command syntax is remove-except [OPTIONS] [KEEP_PATTERN].... Positional arguments specify paths or glob patterns to keep. Positional and stdin patterns use OR semantics; at least one pattern or modification-time bound is required.
First, use --dry-run to review which items will be kept and deleted.
To perform deletion, omit --dry-run. In a normal run, the tool displays the kept items and deletion targets before asking for confirmation. See “Display and Execution” for the confirmation rules. With --force, deletion proceeds without prompting. Invalid patterns or an invalid directory still produce an error.
Use --root to select a different processing directory. Relative paths are resolved from the current directory when the command starts.
Options
| Option | Description |
|---|---|
[KEEP_PATTERN]... |
Paths or glob patterns to keep, combined with OR. Optional when a modification-time bound is supplied. |
--root <PATH> |
Selects the directory to process. Defaults to the current directory when the command starts. Relative paths are resolved from that directory. |
-n, --dry-run |
Displays kept items and deletion targets without deleting anything. |
-f, --force |
Deletes without showing the confirmation prompt. Pattern and directory validation still apply. |
--patterns-from-stdin |
Reads keep patterns from standard input, one per line. They are combined with positional patterns using OR semantics. |
--modified-since <DATE_TIME> |
Inclusive modification-time lower bound. |
--modified-before <DATE_TIME> |
Exclusive modification-time upper bound. |
--format <FORMAT> |
Plan output format: human (default) or json. |
--pager <MODE> |
Built-in viewer: auto (default), always, or never. always conflicts with JSON and --force. |
--layout <LAYOUT> |
Output layout: tree (default) or flat. |
--sort-by-type |
Flat layout only. Sorts by Directory, File, then Symlink. |
--summary <SECTION> |
Shows counts for keep, delete, or both instead of paths in the selected sections. |
-h, --help |
Displays help. |
-V, --version |
Displays the version. |
--summary, --layout, and --sort-by-type are only for human-readable output (--format human) and cannot be combined with --format json.
Keeping by Modification Time
The start is inclusive and the end exclusive; either bound can be omitted. A date denotes local midnight. For an entire November 10 in Japan, use November 10 as the start and November 11 as the end. When patterns are supplied, only regular files matching any pattern and the time range are directly kept, along with their ancestors. A literal directory pattern does not bypass the time condition. Symlinks, empty directories, and special files cannot match directly and may be deleted. Behavior without a time condition is unchanged.
Accepted inputs are YYYY-MM-DD, YYYY-MM-DDTHH:MM, or YYYY-MM-DD HH:MM. Date-times may add :SS and Z or ±HH:MM; omitted seconds are zero. Offsets on dates, fractional seconds, leap seconds, 24:00, lowercase t/z, and -00:00 are rejected. This is a restricted format inspired by RFC 3339. Resolved UTC instants must be at least 1601-01-01T00:00:00Z and before 9999-01-01T00:00:00Z.
Without an offset, the TZ environment variable selects the local zone when set; otherwise the OS zone is detected. Empty or invalid TZ and detection failures are errors. Nonexistent or repeated local times are rejected with guidance to specify an offset. Windows maps its zone to an IANA name, so custom DST settings may not match exactly. Ubuntu needs time-zone data. Resolved bounds appear in previews and the final recap.
Failure to obtain a required modification time aborts without deletion. Times are compared without rounding. A plan is not a snapshot and cannot prevent changes during or after traversal.
On Windows, when a time condition requires checking an item classified as a regular file during traversal, a reparse-point attribute in the retrieved metadata causes exit code 1 before deletion, including in --dry-run. This applies when no patterns are specified or a pattern matches. Items that do not match a pattern are deletion targets without a modification-time check. Excluding a reparse point from the patterns does not keep it; always review the deletion targets.
Patterns and Processing Rules
Example
The following example assumes work is the current directory.
work/
├── keep.txt
├── readme.md
├── todo.txt
├── reports/
│ ├── summary.txt
│ ├── report1.csv
│ ├── report2.csv
│ └── 2025/
│ ├── annual.csv
│ └── notes.txt
└── archive/
└── old.csv
Glob Patterns
You can use glob patterns to specify paths to keep. Characters such as * and ? represent parts of item names or directory levels. Patterns can match files, directories, and symbolic links. Separate multiple patterns with spaces.
In this example tree, readme.md is kept, while keep.txt, todo.txt, reports, and archive are shown as deletion targets. The preview displays both kept items and deletion targets.
Common glob syntax:
| Pattern | Meaning |
|---|---|
*.md |
Item paths ending in .md directly under the processing directory. * does not cross /. |
**/*.md |
Item paths ending in .md directly under the processing directory or in nested directories. **/ matches zero or more directory levels. |
reports/report?.csv |
? matches one Unicode scalar value except /. In this example, it matches report1.csv and report2.csv. |
reports/report[12].csv |
[] matches one listed Unicode scalar value. In this example, it matches report1.csv and report2.csv. |
To limit a glob to a particular subdirectory, include its path relative to the processing directory in the pattern.
In this example tree, the pattern keeps reports/report1.csv, reports/report2.csv, and reports/2025/annual.csv. Quote globs to prevent the shell from expanding them before the command runs.
Selecting Subdirectories
To keep an entire subdirectory, specify its path without a glob.
reports/2025 and all of its contents are kept. For example, annual.csv and notes.txt remain, while reports/summary.txt and reports/report1.csv are deletion targets.
To keep only one file inside a subdirectory, specify its relative path.
This keeps annual.csv and its parent directories, reports and reports/2025. The sibling file notes.txt is a deletion target.
To keep only certain file types within a subdirectory, combine its path with a glob.
This example keeps reports/2025/annual.csv; reports/2025/notes.txt is a deletion target. Since * matches only within one level, reports/2025/*.csv is limited to CSV files directly under reports/2025. To include deeper levels, use reports/2025/**/*.csv. To keep the entire directory, specify its path, such as reports/2025, without a glob.
Processing Scope and Paths
By default, the tool recursively processes the current directory from which it was started. Use --root to select another processing directory. A relative path supplied to --root is resolved from the startup directory. The selected directory itself is never listed or deleted. The filesystem's top-level directory is rejected for safety.
At least one keep pattern or modification-time bound is required. Patterns are positional arguments or, with --patterns-from-stdin, lines read from standard input (see “Pipeline Integration”). With multiple patterns, an item matches if it matches any one of them. Leading or trailing spaces are part of the item name. Quote patterns containing spaces so the shell passes each pattern as one argument.
Relative patterns are resolved from the selected processing directory. Absolute patterns are accepted only when they are inside that directory. Relative patterns and the portion of an absolute pattern after the matching directory prefix normalize . components and repeated separators; the prefix itself is not normalized. On Windows, \ is converted to the / separator before matching. On Ubuntu, \ is not a separator but a glob escape character. Patterns outside the selected directory, patterns containing .. as a path component, empty patterns, and ambiguous Windows drive-relative paths (for example, C:folder) are errors.
Absolute patterns are compared with the processing directory after symbolic links and similar indirections are resolved (the path shown after Root: in the output). If --root or the current directory goes through a link, an absolute pattern written with the link path is treated as outside the processing directory and fails. Use relative patterns in that case.
Matching and Retention
Patterns support *, **, ?, character classes [], and alternation {a,b}. Files, directories, and symbolic links can match. See the examples above for *, **, ?, a character class, and path-separator behavior. See the rest of this section for alternation and retention rules.
? and a character class each match one Unicode scalar value, not one byte or one user-perceived grapheme. A character made from a base character and combining marks therefore requires multiple ? wildcards.
On Ubuntu, ** also matches items whose names contain newlines. Escape a literal backslash as \\; following text such as x80 remains literal, not a hexadecimal escape. Correcting Unicode matching can change keep/delete results compared with the previous byte-based matching on Ubuntu. Review all items with --dry-run and without --summary before deleting.
A matched item and its parent directories are kept, but unmatched descendants are not. A directory path without a glob keeps that directory and all of its contents. dir/* matches only items directly under dir; it does not recursively keep the contents of matched subdirectories. . and ./ keep everything under the processing directory.
The glob characters are *, ?, [, {, and }. On Ubuntu, \ is also a glob character because it escapes the next character. A pattern containing any of them is treated as a glob and does not keep the contents of matched directories. For example, reports/{2024,2025} keeps only the two directories. To keep their contents too, append /**, as in reports/{2024,2025}/**, or specify reports/2024 and reports/2025 separately.
dir/** matches items under dir but not dir itself, so an empty dir becomes a deletion target. To keep a directory even when it is empty, specify dir without a glob.
To match a glob character literally, wrap it in a character class, such as [*], [?], [[], [{], or [}]. For example, x{1}.txt is an alternation that matches x1.txt, so use x[{]1[}].txt for the file with that exact name. An escaped pattern is still a glob, so to also keep the contents of a directory named backup[2025], specify backup[[]2025]/**. An unclosed { or [, or a lone }, is an invalid glob and fails with exit code 2.
Filesystem Behavior
Windows uses the tool's Unicode simple case folding (non-Turkic); Ubuntu is case-sensitive. On Windows, ä and Ä, and ß and ẞ, are treated as equal, but ß and SS are not. The tool does not follow per-directory NTFS case-sensitivity settings. Windows and Ubuntu are supported.
A symbolic link supplied to --root is resolved to its target. Links under the processing directory are not followed and are treated as individual items. If a link is a deletion target, only the link is removed, not its target.
The normalized processing directory and every scanned entry path must be representable as Unicode. Names containing invalid UTF-8 on Ubuntu or unpaired surrogates on Windows stop planning with exit code 1 before any stdout output or deletion. This includes entries that would be kept and applies to human/JSON, Tree/Flat, --summary, --dry-run, and --force. Targets of child symbolic links are not checked. Names containing a valid Unicode replacement character � (U+FFFD) remain accepted.
Display and Execution
The default --layout tree shows kept items and deletion targets as a tree; --layout flat shows ItemType and RelativePath columns. Pattern matches and required ancestors are shown separately from deletion targets. See “Output and Options” for colors, markers, and sorting.
In a normal run, the tool displays both lists before asking for confirmation. Sections selected by --summary show counts instead of path lists. Only a newline-terminated whole-line answer of y or yes (case-insensitive, ignoring surrounding whitespace) deletes. An empty Enter, an unterminated answer at EOF, any other answer, or EOF cancels. The default is No; cancellation exits with code 3. --force skips only this prompt; invalid patterns or an invalid processing directory still produce an error.
If nothing directly matches the keep conditions, a warning is shown and everything under the processing directory becomes a deletion target.
Immediately before the final confirmation in human output, stderr repeats the processing directory, kept count (including required ancestors), direct match count, deletion-item count, and top-level deletion-operation count. No-match and omitted-path warnings are repeated as applicable. This recap does not replace reviewing every item. It is not added for JSON, --force, --dry-run, or plans without deletion targets.
Output and Options
The output starts with a status label and the processing directory. When there are no deletion targets, the label is NO REMOVALS, including in a dry run. Otherwise, dry runs show PREVIEW ONLY, normal runs that require confirmation show CONFIRM TO DELETE, and --force shows FORCE DELETE. On a colored TTY, these labels are highlighted in green, cyan, yellow, and red, respectively. The labels and descriptions remain when color is disabled.
Preview header example:
PREVIEW ONLY Nothing will be removed
Root: S:\work\project
For human-readable output, ordinary Windows drive and UNC paths omit the \\?\ prefix. Paths that would become ambiguous in ordinary notation, such as components ending in a space or period, retain the extended form. Control characters in file names and the processing-directory path are rendered visibly. Display formatting does not change the internal path or deletion targets.
Layouts
| Layout | With color | Without color |
|---|---|---|
| Tree (default) | Directories blue, symbolic links cyan, retained parents that appear only in the deletion list green | / for directories, @ for symbolic links, + for retained parents |
| Flat | ItemType and RelativePath columns; directories blue, symbolic links cyan, files uncolored |
/ on directory paths, @ on symbolic-link paths, no file marker |
Every entry in the deletion list is a deletion target; top-level deletion items are not marked separately. Flat layout has no retained-parent color or marker. Tree layout sorts each directory's immediate children by name and displays each directory subtree contiguously. Flat layout without type sorting uses relative-path order. --sort-by-type requires --layout flat and sorts by Directory, File, then Symlink, with relative-path order within each type. These display orders do not change the plan or deletion order.
Examples:
Legends and Summaries
When a full path listing is shown, a legend appears after the processing-directory path. With color, Tree legends list directories (blue), symlinks (cyan), and retained parents (green); Flat legends list directories (blue) and symlinks (cyan). Without color, Markers: explains /, @, and + for Tree, or / and @ for Flat. On a TTY, --help subtly styles headings, Usage, option names, and values; it emits no ANSI styling when color is disabled.
--summary keep|delete|both replaces selected sections with counts and no paths. Keep counts include required ancestors and separately report direct keep-condition matches. Deletion-item counts and the number of top-level deletion operations are distinct. Since summaries omit paths, review every item with --dry-run and without --summary before deleting.
On a colored TTY, the summary KEEP: heading is bold green and DELETE: is bold red. Headings are unstyled when color is disabled.
In the human format, kept items, deletion targets, and execution results are written to standard output. Warnings, errors, and confirmation prompts are written to standard error (see “JSON Output” for --format json). Human-readable output is not a stable format for parsing by other programs.
Browsing Large Plans
--pager auto (the default) opens the built-in viewer when a normal run or --dry-run produces human output that does not fit the terminal screen. Tree/Flat and summary choices are preserved. Long paths wrap without truncation. The viewer shows the processing directory, status, position, and controls, and reflows when the terminal is resized.
Wrapping preserves grapheme clusters, including combining characters and ZWJ emoji, and measures complete display lines. Actual rendering may vary with the terminal and font. A single cluster wider than a row is also treated as insufficient screen space: before startup, auto explains the fallback to normal output and always exits with code 1; after startup, the viewer stops with code 1 without deleting anything.
The position label shows KEEP when keep-section content is visible, DELETE when delete-section content is visible, KEEP + DELETE when both are visible, or PLAN for introductory information alone. Tab/Shift+Tab cycle through reachable section positions. When both sections have the same destination (for example, the whole plan fits on one screen), they do not scroll.
With color enabled, position labels use bold green for KEEP, bold red for DELETE, and bold cyan for PLAN. KEEP + DELETE colors each label separately; separators and line numbers remain unstyled.
| Key | Action |
|---|---|
| Up / Down | Move one display row |
| PageUp / PageDown | Move one page |
| Home / End | Go to the beginning / end |
| Tab / Shift+Tab | Move between keep / delete sections |
c |
Finish viewing; proceed to a separate final confirmation, or exit with code 0 for dry-run / no deletion targets |
q / Esc / Ctrl+C |
Cancel viewing without deleting anything; exit code 3 |
Enter and y do not authorize deletion in the viewer. On completion, pending viewer input is discarded and terminal state restored before a new, whole-line confirmation answer is read from the controlling terminal. Viewing, confirmation, and deletion use the same plan; this does not prevent other programs from changing files during review.
Immediately before final confirmation, Review before deletion: uses stderr's terminal and color settings: a bold yellow heading, a bold Root: label, bold green KEEP:, and bold red DELETE:. No-match and summary-omission warnings are yellow with bold headings. Paths, counts, and ordinary explanations remain unstyled. Viewer colors use stdout's settings independently of the recap. When color is disabled or the respective stream is redirected, the same wording is shown without styling.
--pager always opens even short listings and conflicts with JSON and --force. --pager never uses normal output. With the default auto mode, JSON and --force (including its combination with --dry-run) do not use the viewer.
If stdout is not a TTY, the controlling terminal is unavailable, the terminal is unsupported, or the screen is too small, auto reports the reason to stderr and uses normal output. Always mode instead exits with code 1 without deleting anything. When a normal run reads its confirmation answer from stdin (not --dry-run, with deletion targets), redirected stdin without --patterns-from-stdin is treated the same way to avoid taking over confirmation input. Dry runs and runs without deletion targets read no confirmation answer, so they can use the viewer with redirected stdin when a supported output terminal and controlling terminal are available. Piped --patterns-from-stdin can use the viewer under the same conditions.
Terminal I/O or restoration failures after starting the viewer stop before deletion with exit code 1 rather than silently continuing with normal output. The viewer does not change keep/delete decisions or deletion order. Search, folding, and interactive plan editing are not supported.
Pipeline Integration
--patterns-from-stdin and --format json let you combine the tool with other commands in PowerShell or Bash. Passing patterns through standard input and receiving the plan as JSON can be used separately or together.
Patterns from Standard Input
With --patterns-from-stdin, standard input is read as one pattern per line.
- Input must be UTF-8. If a line is not valid UTF-8 or contains a NUL character, the command reports its line number and exits with code 2. The command does not detect all BOM-less UTF-16: byte sequences without NUL may be interpreted as different, valid UTF-8 text. A single byte-order mark (BOM) at the start of the input is removed.
- Lines may end with LF or CRLF. Only the line terminator is removed; other whitespace is kept as part of the name. A CR at the end of a final line without a line terminator is also kept.
- Completely empty lines are ignored. A line containing only spaces is treated as a whitespace pattern.
- There is no comment syntax such as
#. - Each line is interpreted as a path or glob, just like a positional argument, not as a literal file name. When file names printed by another command are passed directly, names containing glob characters (
*,?,[,{,}, and\on Ubuntu) may match other items or fail as invalid globs. A directory whose name contains glob characters does not keep its contents. See “Matching and Retention” for escaping and appending/**. - Positional patterns may be combined with stdin patterns; all patterns use OR semantics. The command fails if neither a pattern nor a time bound remains.
- NUL-delimited input is not supported. File names containing newlines cannot be passed as patterns.
- Without a pipe or redirection, you can type patterns in the terminal, one per line. The command writes a note to standard error that it is waiting for input and how to finish. Finish input with Ctrl+D on Ubuntu, or Ctrl+Z followed by Enter on Windows.
Because standard input is used for patterns, the confirmation answer is read from the controlling terminal (the console on Windows, /dev/tty on Ubuntu). When no terminal is available, such as in CI or scheduled jobs, nothing is deleted and the command exits with code 3 (failure to start an explicitly requested --pager always exits with code 1). In that case, preview with --dry-run, or use --force after reviewing the plan. Without --patterns-from-stdin or an active built-in viewer, the confirmation answer is still read from standard input as before.
Bash example (keep only files tracked by Git, plus .git):
|
The git ls-files list does not include .git itself, so the example keeps .git with a positional argument. Without it, the repository's own .git also becomes a deletion target. Untracked and ignored files (such as build output and local settings) become deletion targets, so review every item with --dry-run before running the command for real.
Use this example as is only when tracked file names contain no newlines, tabs, ", \, or glob characters. Even with core.quotePath=false, Git prints names containing newlines, tabs, ", or \ in quotes, so those files do not match and become deletion targets. Names containing glob characters may match other items.
PowerShell example (keep patterns listed in a file, plus *.md):
Get-Content -Encoding UTF8 .\keep-list.txt | remove-except --dry-run --patterns-from-stdin '*.md'
When passing patterns from PowerShell or reading JSON output, use UTF-8 for text exchange. In Windows PowerShell 5.1, $OutputEncoding, which controls text sent to external commands, defaults to ASCII. In PowerShell 7 and later, it defaults to UTF-8, but the setting may have been changed. The following example configures UTF-8 for sending patterns and reading JSON output. No change is needed if the settings already use UTF-8.
$utf8 = [System.Text.UTF8Encoding]::new($false)
$OutputEncoding = $utf8
[Console]::OutputEncoding = $utf8
$OutputEncoding controls how PowerShell sends strings to external commands; [Console]::OutputEncoding controls how PowerShell reads external-command output as strings.
JSON Output
With --format json, the pre-deletion plan is written to standard output as exactly one JSON object. It contains no status label, legend, colors, or warnings. Warnings, confirmation prompts, and messages such as Aborted. and Removal complete. are written to standard error.
| Field | Contents |
|---|---|
schema_version |
Version of the JSON format. Currently 2. |
root |
Absolute path of the normalized processing directory in native OS notation. On Windows it may start with \\?\. |
direct_match_count |
Number of items directly matching all keep conditions. 0 means every item is a deletion target. |
selection |
Input-order patterns and UTC second-precision modified_since and modified_before; absent bounds are null. |
keep_items |
Items matching the keep conditions and their ancestor directories. |
delete_items |
All deletion targets. |
delete_roots |
Top-level deletion items passed to actual deletion. Descendants of deleted directories are not included. |
Each item has relative_path (a /-separated path relative to the processing directory) and type (directory, file, or symlink). Arrays are sorted by relative path. Paths are written as Unicode strings. If any path cannot be represented as Unicode (for example, a name containing invalid UTF-8 on Ubuntu), the command prints no JSON, deletes nothing, and exits with code 1.
--format json output is the plan before deletion, not the result of execution.
- With
--dry-run: the plan is printed and nothing is deleted. - Without
--dry-run: the plan is printed, then confirmation is requested. A cancelled run exits with code 3. Because the JSON is printed before deletion, use the exit code (0for completed deletion,3for cancellation) to tell whether anything was deleted. - With
--force: the plan is printed, then items are deleted without confirmation.
--summary, --layout, and --sort-by-type are for human-readable output and cannot be combined with --format json (exit code 2).
Compatibility: schema 2 generalizes direct_match_count to all keep conditions. Consumers checking schema 1 must update. Fields may be added without changing schema_version; ignore unknown fields.
Bash example (list deletion targets with jq):
|
PowerShell example:
$plan = remove-except --dry-run --format json '**/*.md' | ConvertFrom-Json
$plan.delete_items | Where-Object type -eq 'file' | ForEach-Object relative_path
When reading JSON in PowerShell, also check that it is decoded as UTF-8. See “Patterns from Standard Input” for the configuration example.
Exit Codes
| Exit code | Meaning |
|---|---|
0 |
The plan was shown, or deletion completed (including when there was nothing to delete). |
1 |
Runtime error, such as a scan, modification-time retrieval, time-zone detection or deletion failure, non-Unicode path, or viewer/terminal error. |
2 |
Invalid arguments, standard input, processing directory, patterns, or modification times. |
3 |
Nothing was deleted because viewing or confirmation was cancelled, or no terminal was available to confirm. |
If an error occurs during deletion (exit code 1), items already deleted are not restored.
Versioning and Compatibility
Upgrading from v0.4.0 to v0.5.1
--modified-since(inclusive) and--modified-before(exclusive) add modification-time conditions. Pattern conditions and the time range are combined with AND semantics. Only regular files directly match a time condition; if no file matches, or when links and empty directories are explicitly named, those items may become deletion targets. Before running the command, review every item with--dry-runand without--summary.- JSON now uses schema 2. Consumers that expect schema 1 must update. The library adds
build_plan_with_optionsandModifiedRange. - The MSRV remains Rust 1.88, and Windows and Ubuntu remain supported.
Upgrading from v0.3.0 to v0.4.0
- Non-Unicode path rejection now also applies to human output and the public API, not just JSON. In v0.3.0, human display and matching could collapse different names into the same replacement string. Planning now fails instead of producing an ambiguous preview or keep decision. Library function
build_planreturns no plan and reports a runtime error withoutValidationError. In every execution mode, including--force, the CLI exits with code 1 before stdout, confirmation, or deletion. This is a compatibility change: inputs that previously succeeded may now fail. Names containing a valid Unicode replacement character (U+FFFD) remain supported. - On Ubuntu,
?and character classes now match Unicode scalar values instead of UTF-8 bytes. Combining sequences contain multiple scalar values; Ubuntu matching remains case-sensitive. Keep/delete decisions may differ from earlier versions. Regression tests also cover**matching names containing newlines and patterns containing backslashes. - Fix deletion on an unterminated
y/yesat EOF. The v0.3.0 documentation described Enter to confirm and EOF to cancel, but the distributed implementation also accepted unterminated affirmative answers. Every input path now requires a newline-terminated affirmative line; otherwise, nothing is deleted and the command cancels with exit code 3. - Tree output now keeps each directory subtree contiguous, avoiding duplicate nodes around prefix-sharing siblings. Flat, JSON, and plan relative-path ordering and deletion order are unchanged. Colored summaries show
KEEP:in green andDELETE:in red. - Rust Doc examples now use owned temporary directories. Documentation also clarifies that traversal is not an atomic snapshot and does not prevent concurrent changes. This adds no locking or revalidation guarantee.
- Public API types, JSON
schema_version: 1, MSRV 1.88, and Windows/Ubuntu support remain unchanged. After upgrading, review every item with--dry-runand without--summary.
Upgrading from v0.2.4 to v0.3.0
- Glob classification now includes braces (
{and}) and, on Ubuntu, the backslash escape (\). These patterns no longer get literal-directory recursive retention. Previously retained descendants may become deletion targets:reports/{2024,2025}keeps the matching directories, not their contents; usereports/{2024,2025}/**to keep their descendants too. Review all items with--dry-runand without--summaryafter upgrading. - Confirmation was unified to read a whole line on every input path, normally using
yoryesfollowed by Enter (case-insensitive, surrounding whitespace ignored). However, the v0.3.0 distributed implementation also accepted unterminated affirmative answers; this was fixed in v0.4.0. Cancellation exits with code3rather than0; invalid arguments, stdin input, roots, and patterns exit with code2. Update scripts that depend on exit codes or single-key confirmation. --pager autoadds a viewing step for long terminal output. Use--pager neverfor ordinary output. The viewer does not change keep/delete decisions or deletion order;conly finishes viewing, and Enter oryin the viewer never authorizes deletion. Final confirmation is separate, with a recap on stderr. With stdin patterns or after viewing, confirmation uses the controlling terminal, not stdin.--patterns-from-stdinadds UTF-8 newline-delimited keep patterns;--format jsonadds the pre-deletion plan withschema_version: 1. Human output is not a stable machine-readable interface. Library callers can identify validation failures with the newValidationErrortype.- The minimum Rust version remains 1.88. A plan records entries observed during traversal; the scan is not an atomic or protected filesystem snapshot and does not prevent concurrent changes. The plan is not refreshed after construction, so files may change between preview and deletion. The no-match warning, root validation, and no-follow-symlinks behavior remain in effect;
--forceskips only confirmation.
Updates may change which items are kept or deleted, or how deletion is confirmed. Even a patch update may change deletion results by fixing a bug. Review the changes when updating and inspect the targets with --dry-run before deleting.
License
This project is dual-licensed. You may choose either LICENSE-MIT or LICENSE-APACHE. Dependencies are covered by their respective licenses.
Developer Documentation
For development instructions, see the Development Guide (Japanese, primary) or its English translation.
Some automated tests require symbolic-link creation and fail if it is unavailable. On Windows, this may require Developer Mode or administrator privileges.
The API documentation for published version 0.4.0 is available on docs.rs. The development API may differ from published version 0.4.0.