# remove-except
[English](README.md) | [日本語](README.ja.md)
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, modification times, and file sizes, and deletes the other items under the selected directory.
**Read by task:** [Install](#installation) · [First run and options](#quick-start) · [Patterns](#patterns-and-processing-rules) · [Time and size filters](#shared-time-and-size-rules) · [Output and viewer](#output-and-options) · [stdin, JSON, and exit codes](#pipeline-integration) · [Developer information](#developer-documentation)
## Safety Notice
This tool permanently deletes files and directories.
- Back up important data. Before deleting, run `--dry-run` without `--summary` and review every kept item and deletion target. `--summary` omits paths and is not sufficient for a full review.
- With `--root`, verify that the displayed processing directory is the intended location. A filesystem's top-level directory cannot be selected.
- If no item matches all keep conditions, everything under the processing directory becomes a deletion target. `--force` skips confirmation only; verify the conditions match the intended items. It does not bypass validation or safety guards.
- With modification-time or file-size conditions, explicitly named links and empty directories may still become deletion targets.
- When passing patterns generated by another command with `--patterns-from-stdin`, use `--dry-run` to verify the generated patterns and deletion targets.
## Installation
Choose the method that fits your setup:
- **No Rust toolchain:** use the [prebuilt binaries](#prebuilt-binaries) for a supported environment.
- **Install a published version with Cargo:** use a [published tag](#install-from-source) or [crates.io](#install-from-cratesio).
- **Try development changes:** install from the [default branch](#install-from-source), which may have different features from published releases.
### Prebuilt Binaries
The `v0.6.0` [GitHub Release](https://github.com/tresuke/remove-except/releases/tag/v0.6.0) provides prebuilt binaries for Windows x64 and Linux x64. The older `v0.2.4` release provides source code only.
Version `v0.6.0` adds file-size conditions, opt-in deletion safety guards, and static Bash and PowerShell completions. It also improves terminal-width-aware help. Version `v0.5.1` supports modification-time options and JSON schema 2, but not these additions.
Download the archives and checksums from the GitHub Release **Assets**:
| Platform | Archive | SHA-256 file |
| --- | --- | --- |
| Windows x64 (MSVC) | `remove-except-v0.6.0-x86_64-pc-windows-msvc.zip` | `remove-except-v0.6.0-x86_64-pc-windows-msvc.zip.sha256` |
| Linux x64 (GNU) | `remove-except-v0.6.0-x86_64-unknown-linux-gnu.tar.gz` | `remove-except-v0.6.0-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:
```powershell
Get-FileHash .\remove-except-v0.6.0-x86_64-pc-windows-msvc.zip -Algorithm SHA256
Get-Content .\remove-except-v0.6.0-x86_64-pc-windows-msvc.zip.sha256
```
On Ubuntu, place the archive and checksum in the same directory and run:
```sh
sha256sum --check remove-except-v0.6.0-x86_64-unknown-linux-gnu.tar.gz.sha256
```
Also verify the archive's GitHub Actions build provenance with GitHub CLI, replacing `<archive-path>` with the downloaded archive's path:
```sh
gh attestation verify <archive-path> --repo tresuke/remove-except --signer-workflow tresuke/remove-except/.github/workflows/prepare-release.yml
```
The attestation is registered with GitHub, not supplied as a separate Release asset. Binaries embed dependency crate names and versions using [`cargo-auditable`](https://github.com/rust-secure-code/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:
```powershell
Expand-Archive -LiteralPath .\remove-except-v0.6.0-x86_64-pc-windows-msvc.zip -DestinationPath .\remove-except-v0.6.0
```
```sh
tar -xzf remove-except-v0.6.0-x86_64-unknown-linux-gnu.tar.gz
```
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.6.0` tag:
```sh
cargo install --git https://github.com/tresuke/remove-except --tag v0.6.0 --locked
```
To install the latest default-branch source, omit the tag. It may include changes not present in the published `v0.6.0` release:
```sh
cargo install --git https://github.com/tresuke/remove-except --locked
```
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](https://crates.io/crates/remove-except) for the latest published version and details. Install Rust 1.88 or later and run:
```sh
cargo install remove-except --locked
```
## 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, modification-time bound, or file-size bound is required.
First, use `--dry-run` without `--summary` to review the displayed processing directory, all kept items, and every deletion target.
```sh
remove-except --dry-run keep.txt keep '**/*.md'
```
For a normal run with confirmation, omit `--dry-run`. If the [safety guards](#safety-guards) pass, the tool displays the kept items and deletion targets again, then asks for confirmation if there are deletion targets. Only a newline-terminated whole-line `y` or `yes` confirms. See [Display and Execution](#display-and-execution) for details.
```sh
remove-except keep.txt keep '**/*.md'
```
Use `--force` only when confirmation must be skipped, after reviewing the full dry-run and checking that the conditions match the intended items.
```sh
remove-except --force keep.txt keep '**/*.md'
```
Use `--root` to select a different processing directory. Relative paths are resolved from the startup current directory.
```sh
remove-except --root work --dry-run keep.txt '**/*.md'
```
## Options
This README documents the source in this repository. The `v0.6.0` release tag contains this version's behavior; later default-branch changes may differ. A development build can report the same `--version` as a published build; use `remove-except --help` to check which options are available. Help confirms available features, not where the executable came from. For the exact behavior of published `v0.6.0`, see [that version's README](https://github.com/tresuke/remove-except/blob/v0.6.0/README.md).
| Option | Description |
| --- | --- |
| `[KEEP_PATTERN]...` | Paths or glob patterns to keep, combined with OR. Optional when stdin supplies patterns or a modification-time or file-size bound is supplied. |
| `--root <PATH>` | Selects the processing root. Defaults to the current directory when the command starts ([details](#processing-scope-and-paths)). |
| `-n`, `--dry-run` | Displays kept items and deletion targets without deleting anything ([confirmation flow](#display-and-execution)). |
| `-f`, `--force` | Skips the confirmation prompt, not validation or safety guards ([confirmation flow](#display-and-execution)). |
| `--patterns-from-stdin` | Reads keep patterns from standard input, one per line, and combines them with positional patterns using OR semantics ([details](#patterns-from-standard-input)). |
| `--require-match` | Rejects deletion when no item directly matches all keep conditions ([safety guards](#safety-guards)). |
| `--max-delete-items <N>` | Limits the number of deletion targets ([safety guards](#safety-guards)). |
| `--modified-since <DATE_TIME>` | Modification-time lower bound, inclusive ([details](#keeping-by-modification-time)). |
| `--modified-before <DATE_TIME>` | Modification-time upper bound, exclusive ([details](#keeping-by-modification-time)). |
| `--size-at-least <BYTES>` | Logical file-size lower bound in bytes, inclusive ([details](#keeping-by-file-size)). |
| `--size-below <BYTES>` | Logical file-size upper bound in bytes, exclusive ([details](#keeping-by-file-size)). |
| `--format <FORMAT>` | Plan output format: `human` (default) or `json` ([details](#json-output)). |
| `--pager <MODE>` | Built-in viewer: `auto` (default), `always`, or `never` ([details](#browsing-large-plans)). `always` conflicts with JSON and `--force`. |
| `--layout <LAYOUT>` | Output layout: `tree` (default) or `flat` ([details](#layouts)). |
| `--sort-by-type` | Flat layout only. Sorts by Directory, File, then Symlink ([details](#layouts)). |
| `--summary <SECTION>` | Shows counts for `keep`, `delete`, or `both` instead of paths in the selected sections ([details](#legends-and-summaries)). |
| `--generate-completion <SHELL>` | Writes a static `bash` or `powershell` completion script to stdout ([details](#shell-completion)). |
| `-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`.
### Shell Completion
On Windows, completion supports both `remove-except` and `remove-except.exe` command names.
The command writes only the script to stdout and does not read stdin, build a removal plan, or touch files. It exits `0` on success, `1` if writing fails, and `2` for invalid arguments or shell names. Do not pass keep patterns or execution options such as `--force`. A trailing `--` by itself is accepted, but a keep pattern after it is not. When clap encounters `-h`/`--help` or `-V`/`--version` as an option alongside an otherwise valid completion request, it displays only help or version information, respectively, and exits `0` without generating a script.
**Ubuntu Bash and Windows Git Bash:** Add this to `~/.bashrc` (or to the login startup file if it does not source `~/.bashrc`). Use a trusted `remove-except` executable on `PATH`.
```bash
if _remove_except_completion=$(remove-except --generate-completion bash); then
eval "$_remove_except_completion"
fi
unset _remove_except_completion
```
**Windows PowerShell 5.1 and PowerShell 7 on Windows:** Add this to `$PROFILE` for each shell you use. Use a trusted `remove-except` executable on `PATH`.
```powershell
$removeExceptCompletion = remove-except --generate-completion powershell
if ($LASTEXITCODE -eq 0) {
. ([scriptblock]::Create(($removeExceptCompletion -join "`n")))
}
Remove-Variable removeExceptCompletion
```
Open a new shell and try typing `remove-except --pa` or `remove-except --pager a`, then press Tab, not Enter. Both scripts are static; pressing Tab does not start `remove-except`. Bash uses the standard `clap_complete` Bash generator and follows its completion behavior. PowerShell completes long options and their finite values (space or `=` forms), and stops suggesting them after the `--` argument separator. Single-hyphen short options are not guaranteed to complete in PowerShell, but still work when typed. Neither script supplies application-specific path or keep-pattern suggestions; the shell can offer its own file and directory completions.
### Safety Guards
`--require-match` and `--max-delete-items <N>` apply only when explicitly specified.
- `--require-match` rejects deletion when the direct keep-match count, excluding required ancestor directories, is zero. It also applies when there are no deletion targets.
- `--max-delete-items <N>` compares `delete_items`, including descendants under deletion directories, against N. It does not compare `delete_roots`.
- When both guards are specified, both must pass.
- `--force` cannot bypass either guard.
- Guards evaluate the removal plan after all keep conditions have been applied, including any file-size bounds. They do not rescan the filesystem.
`N` is an ASCII decimal `u64` value; leading zeroes are allowed. Negative values, signs, whitespace, and unit suffixes are rejected. Zero is allowed and permits only plans with no deletion items. Repeating `--max-delete-items` is an invalid argument.
Dry runs report guard violations, but a violation does not itself change the exit code: successful plan display or viewer completion exits 0, viewer cancellation exits 3, and viewer startup or terminal errors exit 1. A dry run never deletes.
On a guard violation, normal and `--force` runs report the violations and rejection on stderr, skip the human-readable preview, viewer, confirmation, and deletion, and exit 3. Human-readable mode writes nothing to stdout on rejection; JSON mode still writes the pre-deletion plan and guard information. The guards evaluate plan-time counts only and do not protect against or detect filesystem changes after planning.
### Shared Time and Size Rules
Version `v0.6.0` supports both modification-time and file-size filters. Version `v0.5.1` supports modification-time filters only.
Multiple patterns use OR semantics; every specified modification-time and file-size bound must also match. If either kind of filter is active, only regular files matching at least one supplied pattern (if any) and every active bound can directly match. Directories, symlinks, and special files cannot directly match. Ancestor directories of directly matched files are kept even when the directories themselves do not match a pattern.
An item that does not match a pattern is not checked for metadata and is normally a deletion target, unless it is an ancestor needed by a directly matched file. A literal directory pattern does not bypass time or size filters. Without either filter, the usual pattern-only rules apply.
Metadata is read only when needed for matching regular files, and only once when both filters need it. Failure to obtain required metadata aborts planning before output or deletion. On Windows, if metadata needed for a time or size check has a reparse-point attribute, the command exits with code 1 before deletion, including in `--dry-run`; this also covers non-symlink reparse points. Excluding such an item from the patterns does not keep it, so review the deletion targets.
A plan is not a filesystem snapshot and cannot prevent changes during or after traversal. See [modification-time bounds](#keeping-by-modification-time) and [file-size bounds](#keeping-by-file-size) for each condition's boundaries and input rules.
### Keeping by Modification Time
```sh
remove-except --dry-run --modified-since 2026-11-10 --modified-before 2026-11-11
remove-except --dry-run --modified-since '2026-11-10T09:00+09:00' '**/*.log'
```
The start is inclusive and the end exclusive; either bound can be omitted. If both are specified, the resolved start must be earlier than the resolved end. A date denotes local midnight. For an entire November 10 in Japan, use November 10 as the start and November 11 as the end.
With a time condition, only regular files matching all active time and size bounds and any supplied pattern can directly match. Symlinks and empty directories cannot match directly and may be deletion targets. See the [shared time and size rules](#shared-time-and-size-rules) for pattern combination, ancestors, and metadata handling.
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.
Times are compared without rounding. See the shared rules for metadata failures and Windows reparse points.
### Keeping by File Size
```sh
remove-except --dry-run --size-at-least 1048576
remove-except --dry-run --size-at-least 1024 --size-below 1048576 '**/*.log'
```
`--size-at-least` keeps files at or above the specified byte count; `--size-below` keeps files below it. Either bound may be used alone. When both are specified, `--size-at-least` must be less than `--size-below`. Values must contain only ASCII decimal digits within the `u64` range. Leading zeroes are allowed; signs, whitespace, and unit suffixes are not. File size means the logical length reported by filesystem metadata, not allocated disk space. `--size-below 0` is invalid because it describes an empty range. `--size-at-least 0` is valid and includes empty files.
With a size condition, only regular files matching every size and time bound and any supplied pattern can directly match. Links and empty directories may become deletion targets. See the [shared time and size rules](#shared-time-and-size-rules) for pattern combination, ancestors, and metadata handling. Size bounds appear in human previews and the final confirmation recap.
## Patterns and Processing Rules
### Example
The following example assumes `work` is the current directory.
```text
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.
```sh
remove-except --dry-run '**/*.md'
```
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.
```sh
remove-except --dry-run 'reports/**/*.csv'
```
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
When neither a modification-time nor a file-size filter is set, specify a subdirectory's path without a glob to keep it and all its contents.
```sh
remove-except --dry-run reports/2025
```
`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.
```sh
remove-except --dry-run reports/2025/annual.csv
```
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.
```sh
remove-except --dry-run 'reports/2025/*.csv'
```
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`.
### 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, modification-time bound, or file-size 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}`. See the examples above for `*`, `**`, `?`, a character class, and path-separator behavior.
`?` 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.
When a modification-time or file-size filter is set, only regular files that satisfy every specified bound and match at least one pattern (if patterns are supplied) are kept, along with their required ancestors. Even a pattern match does not protect a file that fails a filter or an empty directory. For example, with `--size-at-least 1 .`, empty files and empty directories are deletion targets.
The retention rules below apply only when neither filter is set. Files, directories, and symbolic links can match directly. A glob match keeps the matched item and its parent directories, but not unmatched descendants. 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. Items matching the keep conditions and required ancestors are shown separately from deletion targets. See “Output and Options” for colors, markers, and sorting.
In a normal run, if the [safety guards](#safety-guards) pass, the tool displays both lists and asks for confirmation if there are deletion targets. 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:
```text
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:
```sh
remove-except --dry-run --layout flat keep.txt
remove-except --dry-run --layout flat --sort-by-type keep.txt
remove-except --dry-run --summary both keep.txt
```
### 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.
`-h` and `--help` wrap to the detected column width when stdout is a terminal. Widths below 40 columns use 40 columns. Redirected output or an unavailable terminal width uses 80 columns.
`--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.
#### Basic Controls
| 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 in a normal run with deletion targets, 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` never authorize deletion in the viewer. In a normal run with deletion targets, pressing `c` is followed by a separate whole-line confirmation from the controlling terminal.
#### Display and Terminal Details
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.
On completion, pending viewer input is discarded and terminal state restored. If confirmation is needed, it is read afterward. 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.
```sh
remove-except --dry-run --pager always keep.txt
remove-except --pager never keep.txt
```
## 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 no pattern, modification-time bound, or file-size 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, when confirmation is required the answer is read from the controlling terminal (the console on Windows, `/dev/tty` on Ubuntu). If confirmation is required and 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; `--force` skips confirmation. 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`):
```bash
git -c core.quotePath=false ls-files | remove-except --dry-run --patterns-from-stdin .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`):
```powershell
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.
```powershell
$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.
Version `v0.6.0` uses schema 2 and includes guard settings, guard violations, and file-size bounds in `selection`. Published `v0.5.1` also uses schema 2 but does not include these fields; see [that version's JSON specification](https://github.com/tresuke/remove-except/blob/v0.5.1/README.md#json-output).
```json
{
"schema_version": 2,
"root": "/home/user/work",
"direct_match_count": 1,
"guards": { "require_match": false, "max_delete_items": null },
"guard_violations": [],
"selection": { "patterns": ["keep.txt"], "modified_since": null, "modified_before": null, "size_at_least": null, "size_below": null },
"keep_items": [
{ "relative_path": "keep.txt", "type": "file" }
],
"delete_items": [
{ "relative_path": "old", "type": "directory" },
{ "relative_path": "old/a.log", "type": "file" }
],
"delete_roots": [
{ "relative_path": "old", "type": "directory" }
]
}
```
| 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. |
| `guards` | Guard settings. When unspecified: `require_match: false` and `max_delete_items: null`. |
| `guard_violations` | Guard names violated by this plan. `[]` when unspecified or not violated. |
| `selection` | Input-order `patterns`, UTC second-precision `modified_since` and `modified_before`, and integer-byte `size_at_least` and `size_below`; 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.
Size bounds are JSON integers. JavaScript `Number` cannot represent every integer above `Number.MAX_SAFE_INTEGER` (2^53−1) exactly; use arbitrary-precision integers when handling values in that range.
`--format json` output is the pre-deletion plan, not the result of execution. The following applies when there are no other argument or runtime errors.
| Execution | On a guard violation |
| --- | --- |
| `--dry-run` (including with `--force`) | Prints the plan, guard settings, and violations without deleting. A violation alone does not affect the exit code; successful output exits `0`. |
| Normal run (without `--dry-run` or `--force`) | Prints the plan and violations, does not prompt or delete, and exits `3`. If guards pass and there are deletion targets, it prints the plan and then asks for confirmation. |
| `--force` (without `--dry-run`) | Prints the plan and violations, does not delete, and exits `3`. If guards pass, it prints the plan and deletes without prompting. |
`--summary`, `--layout`, and `--sort-by-type` are for human-readable output and cannot be combined with `--format json` (exit code 2).
JSON does not use the viewer. Combining `--pager always` with JSON is invalid (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. JSON always includes `guards` and `guard_violations`, even when no guard is specified. See [Safety Guards](#safety-guards) for human-readable output and dry-run viewer outcomes.
Bash example (list deletion targets with jq):
```bash
remove-except --dry-run --format json '**/*.md' | jq -r '.delete_items[].relative_path'
```
PowerShell example:
```powershell
$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, deletion completed (including when there was nothing to delete), a completion script was generated, or help/version was shown. |
| `1` | Runtime error, such as a scan, metadata retrieval, time-zone detection or deletion failure, non-Unicode path, viewer/terminal error, or completion script output failure. |
| `2` | Invalid arguments, standard input, processing directory, patterns, modification times, or file sizes. |
| `3` | Nothing was deleted because viewing or confirmation was cancelled, or no terminal was available to confirm. Normal and `--force` safety guard violations also use this code. |
A dry-run guard violation does not itself change the exit code. JSON or successful human output exits `0`; viewer cancellation exits `3`, and viewer startup or terminal errors exit `1`.
If an error occurs during deletion (exit code 1), items already deleted are not restored.
## Versioning and Compatibility
### Upgrading from v0.5.1 to v0.6.0
- `--size-at-least` and `--size-below` add opt-in file-size conditions. When used, they can change which regular files match and therefore which items are kept or deleted; without these options, they do not add a size condition.
- `--require-match` and `--max-delete-items <N>` add opt-in safety guards. They reject plans that violate the selected guard settings; `--force` cannot bypass them.
- `--generate-completion <SHELL>` adds static Bash and PowerShell completion scripts. Help output now adapts to terminal width.
- The MSRV remains Rust 1.88, and Windows and Ubuntu remain supported. Review the full plan with `--dry-run` and without `--summary` before deleting.
### Upgrading from v0.4.0 to v0.5.1
- `--modified-since` (inclusive) and `--modified-before` (exclusive) add modification-time conditions. Pattern and time conditions 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-run` and without `--summary`.
- JSON now uses schema 2. Consumers that expect schema 1 must update. The library adds `build_plan_with_options` and `ModifiedRange`.
- 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_plan` returns no plan and reports a runtime error without `ValidationError`. 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` / `yes` at 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 and `DELETE:` 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-run` and 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; use `reports/{2024,2025}/**` to keep their descendants too. Review all items with `--dry-run` and without `--summary` after upgrading.
- Confirmation was unified to read a whole line on every input path, normally using `y` or `yes` followed 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 code `3` rather than `0`; invalid arguments, stdin input, roots, and patterns exit with code `2`. Update scripts that depend on exit codes or single-key confirmation.
- `--pager auto` adds a viewing step for long terminal output. Use `--pager never` for ordinary output. The viewer does not change keep/delete decisions or deletion order; `c` only finishes viewing, and Enter or `y` in 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-stdin` adds UTF-8 newline-delimited keep patterns; `--format json` adds the pre-deletion plan with `schema_version: 1`. Human output is not a stable machine-readable interface. Library callers can identify validation failures with the new `ValidationError` type.
- 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; `--force` skips 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)](https://github.com/tresuke/remove-except/blob/main/DEVELOPMENT.ja.md) or its [English translation](https://github.com/tresuke/remove-except/blob/main/DEVELOPMENT.md).
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 the latest published version](https://docs.rs/remove-except/latest/remove_except/) is available on docs.rs. The development API may differ from the published API.