kaimei - safe, scriptable batch renaming (改名,
"changing a name")
kaimei [options] [-t template]
[-e expr]... [-E] [--mkdir] [-y]
files...
kaimei undo [-n] [run-id]
kaimei history [-v]
kaimei forget [-y] [--older-than age]
[--gone] [--all] [run-id...]
kaimei vars [--match regex] files...
kaimei translit filter [text...]
kaimei renames many files at once, building new names from
a template and/or sed-style expressions. It is built to be safe first:
- Without -y it only prints a preview: old → new, with the
changed part highlighted.
- Nothing is renamed unless the whole batch is valid: no empty names, no two
files given the same name, no name that already belongs to a file outside
the batch.
- It never overwrites anything. Renames use renameat2(2) with
RENAME_NOREPLACE (or check-then-rename where the filesystem lacks
it).
- Swaps and cycles (a→b, b→a) and case-only changes (photo.jpg
→ Photo.jpg) are routed through a temporary name,
.kaimei-tmp-PID-N, so they also work on case-insensitive
filesystems.
- Every applied run is journaled before each rename happens and can be
reverted with kaimei undo, even after a crash or power cut part way
through.
Each new name goes through this pipeline: the -t template
is filled in (without one, the old name is the starting point); that text is
normalized to NFC; the -e expressions run on it in order; the result
is sanitized (see --safe), normalized (NFC, or NFD with
--nfd), and shortened if needed to the 255-byte name limit, cutting
the stem at a character boundary and keeping the extension. Because
sanitizing and normalizing always run, kaimei with no template or
expressions at all is a filename cleaner: names with ? : * etc., or
decomposed (NFD) Unicode, show up in the preview.
Files are renamed in place: every new name stays in the file's own
directory, unless --mkdir lets a / in the new name move the
file into a subfolder. With -E you edit the names yourself in a text
editor (see EDITING).
A template is literal text with fields in braces:
{var[:format][?fallback]...[|filter[:arg]...]...}
For example {n:03}_{stem|lower}.{ext} or {orig.1:02} -
{orig.title|title}.{ext}. Write {{ and }} for literal
braces. A format, fallback or argument that contains ?, |,
: or } goes in double quotes; inside quotes \" is
a quote and every other backslash is kept as it is, so regexes need no extra
escaping: {stem|re:"\s*\(\d+\)$":""}.
Mistakes are reported before anything runs, with a caret under the
problem: unknown variables or filters, a format that doesn't suit the
variable, wrong filter arguments, {orig.N} without a matching
--match group.
- name
- The whole current name.
- stem
- The name without its extension.
- ext
- The extension without the dot, or empty. Directories have none. Under the
default --safe portable a trailing dot is removed, so
{stem}.{ext} also suits files without an extension; with --safe
posix add --trim-dot.
- parent
- The name of the directory the file is in.
- path
- The path as given on the command line (any / in a new name is
replaced, see --safe).
- n
- A counter, in the order of --sort: --start (default 1),
--step (default 1, may be negative), restarting in each directory
with --counter-per-dir.
- size
- Size in bytes.
- size.h
- Size for humans: 512B, 4.2K, 15M, 1.1G (powers of 1024).
- mtime, ctime,
atime
- Last modified, last status change, last accessed; local time (set
TZ to change it). Default format %Y-%m-%d.
- orig.0,
orig.1, ... orig.name
- Captures of --match regex against the current name:
orig.0 is the whole match, numbered and named groups follow.
Missing when the regex doesn't match the name (see --missing).
kaimei vars files prints every variable for each
file, metadata included: the main tool for working out a template.
These are read from the file's contents, and only when the
template uses one: a run with no metadata variable never opens a file.
Values are trimmed and Unicode-normalized; a tag that is empty counts as
missing. A file a reader can't parse (a corrupt tag, a damaged PDF) gets a
warning in the preview and its variables are missing (see --missing).
Each kind of file only goes to its own reader, judged by its first bytes (a
JPEG is never read as audio), with the extension as a fallback for audio
formats that have no header.
Audio (MP3/ID3v2, FLAC, Ogg Vorbis and Opus, M4A, WAV, AIFF,
...):
- title, artist,
album, albumartist, genre, composer
- Text tags, the same names whatever the format (ID3 TIT2, Vorbis TITLE and
MP4 ©nam are all title). title is also a PDF's
title.
- track,
tracktotal, disc, disctotal
- Numbers: a tag of “3/12” gives track 3 and tracktotal 12.
Use a width: {track:02}.
- year
- From whichever date tag the file has.
- duration,
duration.h, bitrate
- Length in seconds, as 3:45 or 1:02:03, and kbit/s. These cost one more
disk seek per file (to the end of an Ogg file).
Images (JPEG, PNG, GIF, WebP, TIFF, HEIF, ...):
- width,
height
- In pixels, as displayed: when EXIF says the photo was taken turned a
quarter turn, they swap.
- exif.date
- When the photo was taken (DateTimeOriginal). It keeps the camera's clock:
with the EXIF time-zone offset, a photo taken at 10:20 in Tokyo is named
10:20 wherever you rename it.
- exif.make,
exif.model, exif.lens
- Camera and lens.
- exif.iso,
exif.fnumber, exif.exposure, exif.focal
- 400, 2.8, 1/250 (a / in a name is replaced; try
{exif.exposure|replace:"/":"-"}), and the focal
length in mm.
PDFs:
- pages,
pdf.title, pdf.author, pdf.subject,
pdf.created
- From the document information; the creation date keeps the document's own
time zone.
- pdf.width,
pdf.height, pdf.paper
- The first page in mm, and its paper size: A3, A4, A5, A6, B4, B5, JIS-B4,
JIS-B5, Letter, Legal, Tabloid or Executive (missing otherwise). These
need a full parse of the file.
PDFs larger than 64 MB, and ones that can't be parsed, are read
with pdfinfo(1) if it is installed.
Videos (MP4, MOV, MKV, WebM, AVI, ...), read by ffprobe(1)
from FFmpeg when it is installed. Without it, MP4-family tags such as
title still come through, and the variables below are missing with a
warning.
- width,
height
- As displayed: a phone video stored sideways with a rotation is the right
way up.
- duration,
duration.h, bitrate, title, artist,
year
- As for audio, from the container.
- vcodec,
acodec
- h264, hevc, vp9, av1; aac, opus.
- fps
- Frame rate: 29.97, 25, 60.
- video.date
- When it was recorded. iPhones store the local time and zone, which is kept
(as for exif.date); otherwise it is the container's creation time,
which is in UTC, shown in local time.
Any file:
- type,
type.ext
- The MIME type from the content and its usual extension, so
{stem}.{type.ext?ext} fixes a wrong extension (and keeps the old
one for plain text, which has no signature).
Content hashes, in lower-case hex. Unlike everything above, these
read the whole file, so a big folder takes a while (on a spinning disk about
as long as copying it); all the hashes a template uses come from one read,
and a progress line shows how far it has got. A directory has no hash (give
a fallback). A length keeps the first digits: {sha256:12}.
- crc32
- CRC-32, 8 digits, as in SFV files and the [1A2B3C4D] of some
release names ({crc32|upper}).
- md5, sha1,
sha256
- As md5sum, sha1sum and sha256sum print them. Files
with the same contents get the same name, so the usual collision check
lists any copies instead of renaming.
- width,
0width
- For numbers: {n:3} pads with spaces to three characters,
{n:03} with zeros (007). On text, a width pads only text made of
digits, such as a captured track number: {orig.1:02}.
- strftime
- For dates: {mtime:%Y%m%d_%H%M}. The usual strftime(3) fields
work: %Y %m %d %H %M %S and %a %b %j %Z %z etc. Without a
format a date is YYYY-MM-DD. Hours are 24-hour: %H gives 15,
%T 15:05:09 and %R 15:05. 12-hour time only appears if you
ask for it with %I or %l and %p (PM) or %P
(pm). Avoid %c, whose layout (2026 M11 18, Wed 15:05:09) suits no
file name.
- length
- For hashes: the first length hex digits, {sha256:12}.
When a variable has no value, each ?fallback is
tried in turn: a quoted string or another variable, as in
{orig.title?stem} or {orig.1?"00"}. The format and
filters apply to whichever value is used. A field that still has no value is
handled by --missing.
Filters run left to right on the field's text.
- lower,
upper
- Change case (Unicode-aware: straße → STRASSE).
- title
- Capitalize each word and lowercase the rest; an apostrophe inside a word
doesn't start a new one (don't → Don't).
- sentence
- Lowercase everything, then capitalize the first letter.
- trim,
trim:chars
- Remove whitespace (or the given characters) from both ends:
{stem|trim:"_-} .
- replace:from:to
- Replace every occurrence of the text from.
- re:regex:replacement
- Replace every match of regex, with the same replacement syntax as
s/// (see EXPRESSIONS):
{stem|re:"(\w+)(\w+)":"$2$1"}. Add
(?i) at the start of the regex to ignore case.
- pad:width[:char]
- Pad on the left to width characters with zeros, or with
char.
- trunc:length
- Keep the first length characters (whole characters: an accented
letter written with a combining mark counts as one).
- slug
- Lowercase, keep letters and digits of any script, turn every other run of
characters into one -: "Hello, World! (Live)" →
hello-world-live.
- nfc, nfkc
- Unicode normalization. nfkc also folds compatibility forms:
full-width ABC → ABC, ① → 1,
half-width ガ → ガ.
Only the text each one is about changes: kanji, digits,
punctuation and other scripts pass through.
- ascii,
ascii:lang
- Fold Latin letters to ASCII: accents are dropped (é → e,
ñ → n), letters without a decomposition are spelled out
(ß → ss, æ → ae, ø → o, þ
→ th, ł → l), and typographic quotes, dashes and the
ellipsis (…) become plain ASCII ones. Æ is Ae before a
lower-case letter and AE among capitals. Profiles: de (ä
ö ü → ae oe ue), da, no (å
ø æ → aa oe ae); sv, fi and the Romance
languages use the generic rules.
- compose
- Turn explicit digraphs into letters: a backslash and a two-character
mnemonic in the style of Vim and RFC 1345, so M\u:ller →
Müller, \e'tude → étude, Espa\n~a
→ España, gro\ssartig → großartig.
kaimei translit --digraphs prints the table. Nothing changes
without a backslash.
- restore:de
- Experimental: guess ae/oe/ue back into ä/ö/ü (Mueller
→ Müller), leaving Michael, Israel, Feuer, neue, Quelle,
aktuell and other listed words alone. Add your own exceptions, one per
line, in ~/.config/kaimei/restore-de.txt. It prints a warning every
time: check the preview.
- hira,
hira:vowel
- Katakana → hiragana (half-width katakana too). ー stays as it
is, or with :vowel becomes the vowel it lengthens:
コーヒー →
こおひい.
- kata
- Hiragana → katakana.
- half, half:kana,
half:ascii
- To half width: カタカナ →
カタカナ (ガ → ガ) and
ABC123 → ABC123. The
options limit it to one of the two.
- full, full:kana,
full:ascii
- To full width: ガ → ガ and ABC →
ABC (a space becomes U+3000). Unlike nfkc,
nothing else changes (① stays ①).
- kana,
kkana
- Romaji → hiragana, or katakana with kkana. Hepburn, Kunrei,
Nihon-shiki and keyboard (IME) spellings are all accepted: shi/si, chi/ti,
tsu/tu, fu/hu, ji/zi, sha/sya, cha/tya, ja/zya/jya, di → ぢ,
du → づ. Small kana are xa or la, xtsu, xya; a doubled
consonant is っ (kitte, matcha); n before a consonant or at the end,
nn, and n' are ん (kan'i → かんい,
konnichiha → こんにちは), and so is m
before b or p (shimbun). ō and ô become おう,
ā ああ; in katakana they and - become ー
(kohi- → コヒー).
- Text is converted word by word, and a word changes only if all of it reads
as romaji, so “Track 01 - tsuki” becomes “Track 01 -
つき”. English words that happen to be valid romaji
(banana, radio) do convert: apply the filter to the part of a name that is
romaji. kkana:loan reads ti, di, tu, du as ティ,
ディ, トゥ, ドゥ instead of チ,
ヂ, ツ, ヅ. :strict makes a word that isn't
romaji an error for that file instead.
- romaji,
romaji:system:long
- Kana → romaji, in lower case (add |title for capitals). The
system is hepburn (default), kunrei or nihon. The
long-vowel style is wapuro (default, or --romaji-long):
spelled as typed on a Japanese keyboard,
とうきょう → toukyou, ぢ
→ di, を → wo, ー → -, ASCII only, and
kana or kkana turn kana-only text back into exactly the same
kana; macron (tōkyō, kōhī);
double (tookyoo); or none (tokyo, which reads best but loses
information). Options go in any order: {stem|romaji:kunrei:macron}.
ん before a vowel or y is written n' (かんい
→ kan'i). Kanji are read first (see yomi), with a space
between the words read and the particles は, へ and を
written as they are said (wa, e, o): 坂本龍一
→ sakamoto ryuuichi, 君の名は → kimi
no na wa, 写真 2024年8月 → shashin 2024nen
8gatsu. Text with no kanji is romanized exactly as it is spelled
(きみのなは → kiminonaha). For no
spaces, use {stem|yomi|romaji}; for the particles as spelled,
{stem|yomi:space|romaji}.
- yomi,
yomi:options
- Kanji → their reading, in hiragana:
東京の天気 →
とうきょうのてんき.
Kana, Latin letters and everything else stay as they are. The text is
split into words by a morphological analyzer (Lindera, with the IPADIC
dictionary built into kaimei), so readings depend on the word:
今日 is きょう, 日本
にっぽん. Numbers keep their digits and the
counter after them is read as a counter: 2024年8月 →
2024ねん8がつ. Options, in any order: kata
gives readings in katakana; space puts a space between words,
keeping particles like て and endings with their word
(上を向いて歩こう →
うえ を むいて
あるこう); particles writes the particles
は, へ and を as they are said, わ, え,
お (romaji does both by itself).
- Kana that isn't joined to any kanji (a name with no kanji at all, or a
word between spaces) is left exactly as written, with no spaces added and
no particles changed: without kanji, where one word ends and the next
begins is only a guess (ひらがな could come out as
ひら が な).
- The dictionary's reading is a good guess, not a certainty, and names
especially can be read several ways (it reads 米津 as
よねつ, not よねづ). Check the
preview, and put corrections in ~/.config/kaimei/readings.csv (see
FILES), which are used before the dictionary. A build without the
kanji feature has no yomi and leaves kanji alone in
romaji.
- tr:name,
tr:name:reverse
- Convert with a table file (see TRANSLITERATION TABLES), or with
:reverse in the other direction. ru-simple (Russian Cyrillic
→ Latin) is built in.
tr:name looks for name.toml or
name.csv in ~/.config/kaimei/translit/, then in
share/kaimei/translit/ next to the installed binary (normally
/usr/local/share/kaimei/translit/), then among the built-in tables.
kaimei translit --list shows what it finds.
The TOML format:
[meta]
name = "ru-simple"
script = "Cyrillic"
direction = "both" # or "forward"
case = "auto" # or "exact"
[map] # longest match wins; order doesn't matter
"щ" = "shch"
"ш" = "sh"
"е" = "e"
"э" = "e"
[reverse] # where the map isn't one-to-one
"e" = "е"
[class] # named sets, for rules
vowel = "аеёиоуыэюя" # a string: any one of its letters
sign = ["ъ", "ь", "й"] # a list: any one of its texts
[[rule]] # a row that applies only in context
from = "е"
to = "ye"
after = ["start", "vowel", "sign"]
Write rows in lower case: with case = auto (the default)
each also gets its Title form and an all-caps form, so щ = shch gives
Щ → Shch, and SHCH among capitals (ЩИ →
SHCHI). A table with direction = both must be reversible: when two
rows produce the same text, the error names them and asks for a
[reverse] row saying which one the text turns back into. Rows that
produce nothing (ъ = "") can't be reversed and are left out
of the reverse direction.
A [[rule]] is a row with a context: it applies only where
the letters around it fit. after says what must come just before the
match, before what must come just after; not_after and
not_before exclude. Each takes a name or a list of names (any one
will do): start (the start of a word: no letter before), end
(the end of a word: no letter after), or a [class] name. A class
written as a string means any one of its characters; as a list of strings,
any one of those texts. Context is matched on the original text, ignoring
case. The example makes е "ye" at the start of a word and
after a vowel, ъ, ь or й
(Елена → Yelena,
подъезд → podyezd),
and "e" elsewhere (текст
→ tekst), as the built-in ru-simple does. At each position the
longest match still wins; a rule beats a [map] row of the same
length, and the first rule that fits beats later ones. case = auto
gives rules Title and all-caps forms too (Е → Ye). Rules work
in the forward direction; for :reverse, a rule's output is one more
row to turn back (ye → е).
A CSV file is the shortcut: one from,to pair per line,
# for comments, double quotes around a field that has a comma or
spaces at either end. It has no [reverse], so :reverse works
only when the table is one-to-one.
kaimei translit --test tr:name text shows each
match, and which rule made it, which helps when writing a table.
- s/regex/replacement/flags
- Substitute. Any delimiter works, as in sed: s|a|b|. A backslash
before the delimiter makes it literal. Flags: g (every match, not
just the first), i (ignore case), x (extended: whitespace
and # comments in the regex are ignored).
- The regex dialect is that of the Rust regex crate: like POSIX ERE
(unescaped ( ) + ? { } |) plus \d \w \s,
(?P<name>...) and Unicode classes. Matching runs in linear
time; there are no backreferences inside the pattern.
- In the replacement, &, $0 and \0 are the whole
match; $1, \1 and ${1} are numbered groups;
${name} is a named group. \U and \L upper- or
lower-case what follows until \E; \u and \l change
only the next character. Use \&, \$ and \\ for
literal characters.
- y/abc/xyz/
- Replace each character of abc with the character at the same
position in xyz. Both must be the same length (in characters, so
y/あい/アイ/ works).
Stem or whole name. By default an expression sees only the
stem (the part before the last dot) and leaves the extension alone, unless
it mentions a literal dot: \. or [.] in an s regex, or
. in a y list. So s/$/_v2/ turns song.flac into
song_v2.flac, while s/\.JPEG$/.jpg/i works on the whole name.
Override with --stem-only or --whole-name. Directories have no
extension.
- -t, --template
template
- Build each new name from a template (see TEMPLATES).
- -e, --expr
expr
- An expression (repeatable; applied in order, after the template).
- -y, --yes
- Apply the renames. Without it nothing changes.
- --match
regex
- Match each name against regex; its captures become {orig.0},
{orig.1}, ..., {orig.name}. Only used with
-t.
- --start n,
--step n
- First value and step of the {n} counter (defaults 1 and 1).
- --counter-per-dir
- Restart {n} in each directory.
- --missing
error|skip|empty
- What happens when a template field has no value and no fallback that has
one. error (the default): the file is listed with an error and
nothing is renamed. skip leaves that file out and renames the rest.
empty uses empty text.
- -R,
--recursive
- Descend into directories given as arguments. Symbolic links are renamed as
links, never followed.
- --include
glob
- Only rename names matching the shell-style glob (*, ?,
[a-z], [!x]). Repeatable; matches the file name, not the
path.
- --exclude
glob
- Skip names matching the glob. With -R, matching directories are not
entered either (e.g. --exclude .git).
- -E, --edit
- Edit the new names in a text editor before the preview; see EDITING.
- --mkdir
- Let a / in the new name move the file into a subfolder of its
directory, creating folders as needed: --mkdir -t
'{artist}/{album}/{track:02} {title}.{ext}'. Only a / written
in the template, an expression or the edit list makes a folder; a /
inside a value (an artist “AC/DC”) is cleaned like any
unsafe character. Each folder name is cleaned on its own (so --safe
windows keeps trailing dots and CON out of folder names too). Refused:
absolute paths, .., empty folder names, a folder path that already
exists as a file, and an existing folder on another filesystem. The
preview lists the new folders; kaimei undo moves the files back and
removes the folders it made, unless something else has been put in them
since. With --mkdir, -e expressions see the whole new path
(folders and name). Files only: it can't be combined with
--dirs.
- --from-encoding
enc
- Read file and folder names that aren't UTF-8 as enc and rename them
to UTF-8: sjis (Shift-JIS, as written by Japanese Windows; also
cp932), eucjp, gbk (GB18030), big5, euckr or
cp1252 (Western European). Without -t, -e or
-E, the name keeps its text and only its encoding changes:
kaimei -R --dirs --from-encoding sjis ~/old-archive previews the
whole tree. With a template or expressions, they see the decoded name, so
the conversion and a rename happen in one step. The preview shows the old
name as it looks today (with “�”) and the new one
with “(from Shift_JIS)”. UTF-8 names are not touched, and
names that aren't valid in enc either are skipped with a message.
kaimei undo puts back the exact original bytes. Without this
option, names that aren't UTF-8 are skipped, and the message shows how a
name reads as Shift-JIS when it does.
- --dirs
- Rename directories too: without -R, the directories given as
arguments; with -R, the ones found inside them (a directory named
with -R is where to look, and is not itself renamed, so a mount
point such as a USB stick stays put). Everything inside a directory is
renamed before the directory itself.
- --hidden
- With -R, include names starting with a dot. Names given on the
command line are always included.
- --sort
name|natural|mtime|size
- Order of the preview and of the renames. Default natural (track2
before track10).
- -i,
--ignore-case
- Case-insensitive matching for every s expression and for
--match.
- --stem-only
- Expressions never see the extension.
- --whole-name
- Expressions always see the whole name.
- --safe
posix|portable|windows
- How strictly new names are cleaned. posix replaces /, NUL
and control characters. portable (the default) also replaces
< > : " \ ? * | and removes trailing dots and spaces and
a leading -, which suits USB sticks and Samba shares.
windows also defuses the reserved DOS names (CON, PRN, AUX, NUL,
COM1–COM9, LPT1–LPT9, with any extension) by appending the
replacement.
- --replace-char
str
- What an unsafe character becomes. Default _; may be empty to delete
them.
- --fullwidth
- Replace unsafe punctuation with its full-width form
(:?/* and so on) instead, which looks natural
in Japanese names.
- --nfd
- Write names in Unicode NFD instead of NFC.
- --ci
- Treat names that differ only in case as colliding. Use it when the files
are on, or will be copied to, a case-insensitive filesystem (vfat, exFAT,
NTFS).
- -j, --jobs
n
- How many files to read metadata from at once. The default, 0, reads one at
a time when the files are on a spinning disk and up to 8 at once
otherwise. On a hard disk reading is seek-bound (about 9 ms a file, so 45
seconds for 5,000 tracks the first time; a second preview of the same
files is instant) and more jobs don't make it faster.
- --romaji-long wapuro|macron|double|none
- How romaji writes long vowels when the template doesn't say
(default wapuro).
- --trim-dot
- Remove any dots left at the end of a new name, such as the one
{stem}.{ext} leaves on a file with no extension. The
portable and windows profiles already do this; it matters
with --safe posix.
- --no-fullwidth,
--no-nfd, --no-ci, --no-trim-dot
- Turn the matching setting off for this run, overriding the config file.
When both forms are given, the later one wins.
- --show-unchanged
- Also list files whose name stays the same.
- --config
file
- Read defaults from file instead of
~/.config/kaimei/config.toml.
- --no-config
- Ignore the config file.
- --color
auto|always|never
- Highlight the preview. auto colours when writing to a terminal and
NO_COLOR is not set.
-E (--edit) opens the list of names in your editor
($VISUAL, else $EDITOR, else vi), one per line after a
number, under a heading for each folder:
# music/album/
001 01 song.mp3
002 02 other song.mp3
The names are the ones kaimei would give: the current names, or
what -t and -e make of them, so a template can do most of the
work and you fix the rest by hand. Change the names, save and quit. kaimei
then shows the usual preview, and asks whether to rename, edit again or stop
(with -y it renames straight away; without a terminal, and without
-y, it only previews).
Keep each line's number. Deleting a line, or putting back the old
name, leaves that file alone; unlike vidir, nothing is ever deleted. Names
you type are cleaned like any other (--safe), checked for collisions
and journaled, so kaimei undo works as usual. With --mkdir, a
/ in a name moves the file into that folder. If the list has a
mistake (a missing number, one number twice), kaimei says which line and
offers to edit it again; if you stop, the list is kept (in
$XDG_RUNTIME_DIR or /tmp) so your edits aren't lost.
- kaimei undo
[-n] [run-id]
- Revert a run. Without an id, the newest rename run that hasn't been
undone. An undo is itself a journaled run, so undoing it (by its id)
redoes the original. Undo never overwrites: if something now occupies an
old name, that file is reported and left alone, the rest are restored, and
running the same undo again later finishes the job. When you undo an older
run by its id, a name that a later run has renamed since is left alone
(what is there now is not that run's file): undo the later run first, then
the older one again. -n (--dry-run) shows what would
happen.
- kaimei forget
[-y] [--older-than age] [--gone]
[--all] [run-id...]
- Delete run journals: the runs named, those older than age
(90d, 12w, 6m, 2y; a bare number is days), or
all of them. Journals are never deleted otherwise. Without -y it
only lists what would go. A forgotten run can no longer be undone, so a
run that stopped part way and hasn't been undone is kept unless you name
it. --gone picks the runs with nothing left to undo: none of their
files are still at the names the run gave them (moved, deleted, renamed
again, or already undone). Files on a drive that isn't plugged in look the
same; the list says when a run's folders are missing too, so read it
before adding -y. With --older-than, both must hold.
- kaimei vars
[--match regex] [-i] [-j n]
[--hash] files...
- Print every template variable and its value for each file (directories
included), metadata and any problems reading it too, with the
orig.* captures if --match is given. The main tool for
working out a template. The hashes are shown only with --hash,
since they read every file in full.
- kaimei translit
filter [text...]
- Run one filter, written as in a template (romaji:macron,
ascii:de, tr:ru-simple, lower), on the text, or on
each line of standard input, and print the result: kaimei translit
romaji:macron とうきょう prints
tōkyō. --list shows the transliteration filters and
the tables found, --digraphs the compose table, and
--test tr:name each step of a table conversion.
- kaimei history
[-v]
- List journaled runs, oldest first, with the command line that made them.
-v lists every rename; ? marks one interrupted by a crash
and ! one that failed.
A file literally named undo or history can be
renamed as ./undo.
Defaults for options can be set in
$XDG_CONFIG_HOME/kaimei/config.toml (usually
~/.config/kaimei/config.toml). Options on the command line always
win: a value option such as --safe windows replaces the configured
value, and each on/off setting has a --no- form (--no-ci,
--no-trim-dot, ...) to switch it off for one run. An unknown key is
an error, so a typo doesn't go unnoticed.
safe = "portable" # posix | portable | windows
replace-char = "_"
fullwidth = false
sort = "natural" # name | natural | mtime | size
missing = "error" # error | skip | empty
color = "auto" # auto | always | never
ci = false
nfd = false
trim-dot = false
romaji-long = "wapuro" # wapuro | macron | double | none
start = 1
step = 1
jobs = 0 # 0 = automatic
A commented example is installed as
/usr/local/share/kaimei/config.toml.example.
- $XDG_STATE_HOME/kaimei/runs/RUN-ID.jsonl
- One journal per applied run (default ~/.local/state/kaimei/runs).
Run ids are the UTC start time, YYYYMMDD-HHMMSS. Each line is a JSON
object; a rename's line is written and synced to disk before the rename
happens.
- ~/.config/kaimei/translit/NAME.toml, NAME.csv
- Your transliteration tables.
- ~/.config/kaimei/readings.csv
- Your kanji readings, used by yomi and romaji before the
dictionary: one word,reading per line (a tab works too), the
reading in hiragana or katakana, # for comments. A space in the
reading becomes a space between words with yomi:space and in
romaji:
- ~/.config/kaimei/restore-de.txt
- Extra words for restore:de to leave alone, one per line.
- /usr/local/share/bash-completion/completions/kaimei,
/usr/local/share/zsh/site-functions/_kaimei,
/usr/local/share/fish/vendor_completions.d/kaimei.fish
- Shell completion for options, filter names and so on (kaimei
completions bash|zsh|fish prints them).
- $XDG_RUNTIME_DIR/kaimei-edit-PID.txt
- The list -E opens (in /tmp without $XDG_RUNTIME_DIR),
readable only by you; removed afterwards unless the run stopped.
- /usr/local/share/kaimei/translit/
- Installed tables, including the ru-simple example.
- /usr/local/share/doc/kaimei-bin/IPADIC-NOTICE.txt
- The licence of the IPADIC dictionary built in for kanji readings.
- 0
- Success, or a clean preview.
- 1
- Nothing was renamed: a usage or expression error, a file that can't be
read, or a batch that failed validation.
- 2
- A run stopped part way (for example, permission denied). The journal is
complete; kaimei undo reverts what was done.
Every command here only previews; add -y to rename, and
kaimei undo takes a run back. An indented line under a command shows
what it does to one file.
Remove text, then apply:
kaimei -e 's/IMG_//' *.jpg
IMG_0042.jpg → 0042.jpg
kaimei -e 's/IMG_//' -y *.jpg
Spaces to underscores, and a uniform extension (the second
expression mentions \., so it sees the extension):
kaimei -e 's/ +/_/g' -e 's/\.JPE?G$/.jpg/i' *
my holiday photo.JPEG → my_holiday_photo.jpg
Lower case, Title Case, or a web-friendly slug:
kaimei -t '{stem|lower}.{ext|lower}' *
Holiday.JPG → holiday.jpg
kaimei -t '{stem|title}.{ext}' *
the long road.mp3 → The Long Road.mp3
kaimei -t '{stem|slug}.{ext}' *
Hello, World! (Live).mp3 → hello-world-live.mp3
Strip the " (1)" a browser adds to a second
download:
kaimei -t '{stem|re:"\s*\(\d+\)$":""}.{ext}' *
report (1).pdf → report.pdf
Swap "Artist - Title" around, title-casing words with
\u:
kaimei -e 's/^(.+) - (.+)$/$2 - $1/' -e 's/\w+/\u&/g' *.mp3
queen - bohemian rhapsody.mp3 → Bohemian Rhapsody - Queen.mp3
A three-digit counter in front:
kaimei -t '{n:03}_{stem}.{ext}' *.jpg
beach.jpg → 001_beach.jpg
Number scans in the order they were made, oldest first, or count
in tens from 10:
kaimei --sort mtime -t 'scan_{n:03}.{ext}' *.pdf
kaimei --start 10 --step 10 -t '{n:03} {stem}.{ext}' *
A date and a counter:
kaimei --sort mtime -t '{mtime:%Y%m%d}_{n:03}.{ext|lower}' *.JPG
romaji turns kanji, hiragana and katakana into romaji.
Kanji are read with the built-in dictionary first, with a space between the
words:
kaimei -t '{stem|romaji}.{ext}' *
東京の天気.txt → toukyou no tenki.txt
Before renaming, try a filter on some text with kaimei
translit; whatever works there works in {stem|...}:
kaimei translit romaji 坂本龍一
→ sakamoto ryuuichi
kaimei translit romaji:none 坂本龍一
→ sakamoto ryuichi
Pick a long-vowel style: wapuro (the default: toukyou, as
typed on a Japanese keyboard, and converts back exactly), macron
(tōkyō), double (tookyoo) or none (tokyo). Add
|title for capitals, or |slug for lower case with hyphens:
kaimei -t '{stem|romaji:macron}.{ext}' *
東京の天気.txt → tōkyō no tenki.txt
kaimei -t '{stem|romaji:none|title}.{ext}' *
東京の天気.txt → Tokyo No Tenki.txt
kaimei -t '{stem|romaji:none|slug}.{ext}' *
ローマ字 テスト.txt → romaji-tesuto.txt
kaimei -t '{stem|romaji:kunrei}.{ext}' *
写真.jpg → syasin.jpg
When a name has kanji, the particles は, へ and
を come out as said (wa, e, o). To keep them as spelled, read the
kanji with yomi:space first:
kaimei -t '{stem|romaji|title}.{ext}' *
君の名は.mp3 → Kimi No Na Wa.mp3
kaimei -t '{stem|yomi:space|romaji|title}.{ext}' *
君の名は.mp3 → Kimi No Na Ha.mp3
Numbers keep their digits, and the counters after them are read as
counters. A name with no kanji is romanized as it is spelled, and no spaces
are added to it:
kaimei -t '{stem|romaji}.{ext}' *
写真 2024年8月.jpg → shashin 2024nen 8gatsu.jpg
ひらがな テスト.txt → hiragana tesuto.txt
Without spaces between the words:
kaimei -t '{stem|yomi|romaji}.{ext}' *
東京の天気.txt → toukyounotenki.txt
Only part of the name: here the track number and the title stay,
and only the artist is romanized (a template can apply a filter to a
--match capture):
kaimei --match '^(\d+) (.+) - (.+)\.' \
-t '{orig.1} {orig.2} - {orig.3|romaji|title}.{ext}' *
01 Intro - 坂本龍一.mp3 → 01 Intro - Sakamoto Ryuuichi.mp3
A reading is wrong (names especially): add the word and its
reading to ~/.config/kaimei/readings.csv and check it. A space in the
reading separates words:
echo '米津玄師,よねづ けんし' >> ~/.config/kaimei/readings.csv
kaimei translit romaji 米津玄師
Kanji to kana, in hiragana or katakana:
kaimei -t '{stem|yomi}.{ext}' *
東京の天気.txt → とうきょうのてんき.txt
kaimei -t '{stem|yomi:kata}.{ext}' *
東京.txt → トウキョウ.txt
The other way: romaji to hiragana or katakana. A word converts
only if all of it is romaji, so English words and numbers stay:
kaimei -t '{stem|kana}.{ext}' *
Track 01 - tsuki.mp3 → Track 01 - つき.mp3
kaimei -t '{stem|kkana}.{ext}' *
toukyou.txt → トウキョウ.txt
Hiragana and katakana, and full- and half-width forms:
kaimei -t '{stem|kata}.{ext}' *
ひらがな.txt → ヒラガナ.txt
kaimei -t '{stem|hira}.{ext}' *
カタカナ.txt → かたかな.txt
kaimei -t '{stem|nfkc}.{ext}' *
ABC123 カタカナ.txt → ABC123 カタカナ.txt
kaimei -t '{stem|half:ascii}.{ext}' *
DSC01.jpg → DSC01.jpg
A whole music tree, folders included. A folder's stem is
its whole name and its ext is empty, so the same template works for
both:
kaimei -R --dirs -t '{stem|romaji:none|title}.{ext}' ~/music/j-pop
坂本龍一 → Sakamoto Ryuichi
Titles from the tags, artist and title both:
kaimei -t '{artist|romaji|title} - {title|romaji|title}.{ext}' *.mp3
Names from an old Windows archive or zip that show up as garbage
are often Shift-JIS; convert them to UTF-8 (undo puts the old bytes
back):
kaimei -R --dirs --from-encoding sjis ~/old-archive
kaimei -t '{stem|ascii}.{ext}' *
Café Señor.txt → Cafe Senor.txt
kaimei -t '{stem|ascii:de}.{ext}' *
Müller.txt → Mueller.txt
kaimei -t '{stem|tr:ru-simple}.{ext}' *
Елена.txt → Yelena.txt
kaimei -t '{stem|compose}.{ext}' *
M\u:ller.txt → Müller.txt
Plain ASCII for an old device, German style, with Japanese
romanized too:
kaimei -t '{stem|ascii:de|romaji:none}.{ext}' *
Müller 東京.txt → Mueller tokyo.txt
kaimei vars file shows every variable a file has.
Name music from its tags, leaving untagged files alone:
kaimei -R -t '{track:02} - {title}.{ext}' --missing skip ~/music/album
Multi-disc albums, with disc 1 when the tag is missing:
kaimei -t '{disc?"1"}-{track:02} {title}.{ext}' *.flac
Photos by when they were taken, with the camera model:
kaimei -t '{exif.date:%Y%m%d_%H%M%S}_{exif.model|slug}.{ext|lower}' *.JPG
Phone videos by recording time, with their resolution:
kaimei -t '{video.date:%Y%m%d_%H%M%S}_{width}x{height}.{ext|lower}' *.mp4
PDFs by their title (or the old name when there is none) and page
count:
kaimei -t '{pdf.title?stem} ({pages}p).{ext}' *.pdf
Fix extensions that lie about the file:
kaimei -t '{stem}.{type.ext?ext}' *
Add the CRC-32 to video names, or name files by content to find
copies (copies get the same name, so the preview lists them):
kaimei -t '{stem} [{crc32|upper}].{ext}' *.mkv
kaimei -t '{sha256:16}.{ext}' ~/inbox/*
Rebuild "Track 7 - some title.flac" as "07 Some
Title.flac", leaving files that don't fit the pattern alone:
kaimei --match '^Track (\d+) - (?P<t>.+)\.' \
-t '{orig.1:02} {orig.t|title}.{ext}' --missing skip *.flac
Track 7 - some title.flac → 07 Some Title.flac
Swap two numbers:
kaimei -e 's/(\d+)-(\d+)/$2-$1/' *
2024-11.pdf → 11-2024.pdf
Sort music into folders by its tags (a / inside a tag stays part
of the name):
kaimei --mkdir -t '{albumartist?artist}/{album}/{track:02} {title}.{ext}' *.flac
Photos into year/month folders:
kaimei --mkdir -t '{exif.date:%Y}/{exif.date:%m}/{stem}.{ext}' *.JPG
Only some files in a tree:
kaimei -R --include '*.mp3' --exclude 'demos' -t '{stem|lower}.{ext}' ~/music
Make a tree safe for a FAT USB stick, directories included:
kaimei -R --dirs --safe windows --ci ~/stick-copy
Let a template do most of the work, then fix the rest in your
editor:
kaimei -E -t '{track:02} {title}.{ext}' *.mp3
kaimei -E -t '{stem|romaji}.{ext}' *
kaimei undo # the last run
kaimei undo -n # only show what it would put back
kaimei history -v # every run, and every rename in it
kaimei undo RUN-ID # an older run
File names that are not valid UTF-8 are skipped unless
--from-encoding says what they are, and one run reads them all in the
same encoding. Names that are already UTF-8 but garbled (Shift-JIS bytes
read as another encoding and saved as UTF-8 by an unzip tool) are not
repaired. Files can't be moved to another filesystem, or with --mkdir
above their own folder.
Kanji readings are the dictionary's best guess (see yomi).
Text with no kanji is romanized by its spelling: the particles stay ha, he
and wo, and no spaces are added. Kana joined to kanji is split where the
analyzer thinks the words break, which can be wrong for a word it doesn't
know (東京のひらがな →
toukyou no hira ga na). おう across a word boundary
(思う) is still treated as a long vowel by macron,
double and none. restore:de is guesswork. Scripts other
than Latin and Japanese need a table file.
mv(1), sed(1), strftime(3),
rename(2)