remove-except 0.4.0

A Rust CLI to keep selected paths or glob matches and remove everything else under a root.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
# 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` is a command-line tool that keeps items matching any supplied path or glob pattern 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 none of the supplied keep patterns matches any item, everything under the selected directory becomes a deletion target. Especially when using `--force`, verify that the intended patterns 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.

## Installation

### Prebuilt Binaries

The `v0.4.0` [GitHub Release](https://github.com/tresuke/remove-except/releases/tag/v0.4.0) provides prebuilt binaries for Windows x64 and Linux x64. The older `v0.2.4` release provides source code only.

Download the archive for your platform and its matching checksum from that Release's **Assets**:

| Platform | Archive | SHA-256 file |
| --- | --- | --- |
| Windows x64 (MSVC) | `remove-except-v0.4.0-x86_64-pc-windows-msvc.zip` | `remove-except-v0.4.0-x86_64-pc-windows-msvc.zip.sha256` |
| Linux x64 (GNU) | `remove-except-v0.4.0-x86_64-unknown-linux-gnu.tar.gz` | `remove-except-v0.4.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.4.0-x86_64-pc-windows-msvc.zip -Algorithm SHA256
Get-Content .\remove-except-v0.4.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.4.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.4.0-x86_64-pc-windows-msvc.zip -DestinationPath .\remove-except-v0.4.0
```

```sh
tar -xzf remove-except-v0.4.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.4.0` tag:

```sh
cargo install --git https://github.com/tresuke/remove-except --tag v0.4.0 --locked
```

To install the development version, omit the tag and use the latest default-branch source. It may differ from the published `v0.4.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

These instructions do not indicate that publication on crates.io is complete. Check the [remove-except 0.4.0 page](https://crates.io/crates/remove-except/0.4.0) for publication status. If it has not been published, this installation method is unavailable; use the Git-tag installation method above instead.

If version `0.4.0` is published on crates.io, install Rust 1.88 or later and run:

```sh
cargo install remove-except --version '=0.4.0' --locked
```

## Quick Start

The command syntax is `remove-except [OPTIONS] [KEEP_PATTERN]...`. Positional arguments specify paths or glob patterns to keep. With `--patterns-from-stdin`, provide at least one pattern across both sources; multiple patterns use OR semantics.

First, use `--dry-run` to review which items will be kept and deleted.

```sh
remove-except --dry-run keep.txt keep '**/*.md'
```

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.

```sh
remove-except keep.txt keep '**/*.md'
remove-except --force keep.txt keep '**/*.md'
```

Use `--root` to select a different processing directory. Relative paths are resolved from the current directory when the command starts.

```sh
remove-except --root work --dry-run keep.txt '**/*.md'
```

## Options

| Option | Description |
| --- | --- |
| `[KEEP_PATTERN]...` | Paths or glob patterns to keep. At least one is required unless `--patterns-from-stdin` is used; multiple patterns use OR semantics. |
| `--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. |
| `--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`.

## 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

To keep an entire subdirectory, specify its path without a glob.

```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`. 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 is required. Patterns are positional arguments or, with `--patterns-from-stdin`, lines read from standard input (see “Pipeline Integration”). With multiple patterns, an item is kept 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 none of the supplied keep patterns matches any item, 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.

`--summary keep|delete|both` replaces selected sections with counts and no paths. Keep counts include required ancestors and separately report direct pattern 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.

```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. If no pattern remains after empty lines are ignored, the command fails.
- 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`):

```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.

```json
{
  "schema_version": 1,
  "root": "/home/user/work",
  "direct_match_count": 1,
  "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 `1`. |
| `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 matched by a pattern. `0` means every item is a deletion target. |
| `keep_items` | All kept items, including pattern matches 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 (`0` for completed deletion, `3` for 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: fields may be added without changing `schema_version`; ignore unknown fields. Breaking changes, such as removing a field or changing its meaning, increment `schema_version`.

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, or deletion completed (including when there was nothing to delete). |
| `1` | Runtime error, such as a scan or deletion failure, a non-Unicode path, failure to start an explicitly requested viewer, or a terminal error during viewing. |
| `2` | Invalid arguments, standard input, processing directory, or patterns. |
| `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.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).

Publication of the public library API reference on docs.rs is planned, but it is not available yet.