Skip to content
프로젝트

소개

A practical cross-platform command-line tool for safely batch renaming files/directories via regular expression

개발 도구

이 수치를 측정하는 방법

What you can do

  • Windows file systems, including NTFS and FAT, are case-insensitive. Some operations are allowed on Linux, while they could be dangerous on Windows. For example, renaming test.tar.gz to test.tar will overwrite TEST.tar. brename (v2.13.0 and later versions) can handle these cases appropriately (-w and -W).
  • New path existed: Existing files might be overwritten, causing data loss.
  • Overwriting newly renamed path. Existing files might be overwritten, causing data loss. This case is hard to check by eye.
  • Missing target: The new filename is empty, which is not allowed.

측정된 스타 증가

in 24h
0
in 7 days
0
in 15 days
+1
in 1 month
기록 수집 중

서로 겹치는 기간의 순증가량이며 일별 합계가 아닙니다. 측정값이 없으면 비워 둡니다. 스타는 관심도를 나타내며 품질을 보장하지 않습니다.

README.md

Original

brename: batch renaming safely

Built with GoLang Cross-platform Latest Version Github Releases

brename is a cross-platform command-line tool for safely batch renaming files/directories via regular expressions.

Table of Contents

Features

  • Cross-platform. Supports Windows, Mac OS X and Linux.

    • Windows file systems, including NTFS and FAT, are case-insensitive. Some operations are allowed on Linux, while they could be dangerous on Windows. For example, renaming test.tar.gz to test.tar will overwrite TEST.tar. brename (v2.13.0 and later versions) can handle these cases appropriately (-w and -W).
  • Safe. It helps you check for potential conflicts and errors before it's too late.

    Some common conflicts and errors that might happen with commands like mv or rename:

    • New path existed: Existing files might be overwritten, causing data loss.
    • Overwriting newly renamed path. Existing files might be overwritten, causing data loss. This case is hard to check by eye.
    • Missing target: The new filename is empty, which is not allowed.
    • New path ending with a space: Not allowed in Windows. It's legal in Linux, but might cause unexpected errors.
    • New path ending with a period: Not allowed in Windows.
  • Supporting dry runs. A good habit.

  • Supporting Undo for the last rename operation, including completed moves from a failed run.

  • Overwrites can be detected and users can choose whether to overwrite or skip them (-o/--overwrite-mode).

  • File filtering.

    • Supports including (-f/--include-filters) and excluding (-F/--exclude-filters) files via regular expressions.
    • No need to run commands like find ./ -name "*.html" -exec CMD.
  • Renaming submatches with corresponding values via a key-value file (-r "{kv}" -k kv.tsv).

  • Renaming via ascending integers (-r "{nr}").

  • Automatically making directories: e.g., renaming a-b-c.txt to a/b/c.txt.

  • Recursively renaming both files and directories (-R/--recursive, -D/--including-dir, --only-dir).

Installation

brename is implemented in the Go programming language; executable binary files for most popular operating systems are freely available on the releases page.

Method 0: Conda

Install conda, then run

conda install -c conda-forge brename

Or use mamba, which is faster.

mamba install -c conda-forge brename

Method 1: Download binaries

brename v2.15.0 Github Releases (by Release)

Tip: run brename -V to check for updates!

Version checks wait up to 30 seconds for GitHub and report network or HTTP errors. A release that differs from the installed version is shown as the latest release; it may be older than a local development build.

OS Arch File Download Count
Linux 32-bit brename_linux_386.tar.gz Github Releases (by Asset)
Linux 64-bit brename_linux_amd64.tar.gz Github Releases (by Asset)
Linux arm64 brename_linux_arm64.tar.gz Github Releases (by Asset)
OS X 64-bit brename_darwin_amd64.tar.gz Github Releases (by Asset)
OS X arm64 brename_darwin_arm64.tar.gz Github Releases (by Asset)
Windows 32-bit brename_windows_386.exe.tar.gz Github Releases (by Asset)
Windows 64-bit brename_windows_amd64.exe.tar.gz Github Releases (by Asset)
Windows arm64 brename_windows_arm64.exe.tar.gz Github Releases (by Asset)

Just download the compressed executable file for your operating system, and decompress it with the tar -zxvf *.tar.gz command or other tools. And then:

  1. For Linux-like systems

    1. If you have root privileges, simply copy it to /usr/local/bin:

       sudo cp brename /usr/local/bin/
      
    2. Or copy it to a directory listed in the environment variable PATH:

       mkdir -p $HOME/bin/; cp brename $HOME/bin/
      
  2. For Windows, just copy brename.exe to C:\WINDOWS\system32.

Method 2: Homebrew

brew install brename

Method 3: For ArchLinux AUR users

yaourt -S brename

Method 4: For Scoop users

scoop install brename

Method 5: Compiling from source

Go 1.26.0 or later is required.

# download Go from https://go.dev/dl
wget https://go.dev/dl/go1.27.3.linux-amd64.tar.gz

tar -zxf go1.27.3.linux-amd64.tar.gz -C $HOME/

# or 
#   echo "export PATH=$PATH:$HOME/go/bin" >> ~/.bashrc
#   source ~/.bashrc
export PATH=$PATH:$HOME/go/bin

git clone https://github.com/shenwei356/brename
cd brename

go build

# or statically-linked binary
CGO_ENABLED=0 go build -tags netgo -ldflags '-w -s'

# or cross compile for other operating systems and architectures
CGO_ENABLED=0 GOOS=openbsd GOARCH=amd64 go build -tags netgo -ldflags '-w -s'

Run sh packaging.sh from the repository root to create release archives in binaries/, with MD5 checksums in .tar.gz.md5.txt files. The script builds amd64 and arm64 binaries for Linux, macOS, and Windows. All builds and checksums finish in a temporary directory before release files are replaced. Build failures leave existing archives untouched.

For development, run go test ./.... Case-insensitive path tests require a writable case-insensitive filesystem for temporary files. Set TMPDIR (TMP on Windows) to a directory on that filesystem, then run:

go test -v -run 'TestCLICaseInsensitiveAliases|TestCLIForceUndoCaseInsensitiveParent' ./...

These tests report SKIP on a case-sensitive filesystem; a skipped case does not verify that behavior. Cross-compiling also does not run these filesystem checks.

Usage


brename: a practical cross-platform command-line tool for safely batch renaming files/directories via regular expression

Version: 2.16.0

Author: Wei Shen <[email protected]>

Homepage: https://github.com/shenwei356/brename

Warnings:
  1. The path in file systems like FAT32 or NTFS is case-insensitive, so you should switch on the flag
     -w/--case-insensitive-path to correctly check file overwrites.
  2. The flag -w/--case-insensitive-path is switched on by default on Windows, please use
     -W/--case-sensitive-path to disable it if the file system is indeed case-sensitive.
  3. After path normalization, new names ending with periods or spaces are not allowed.
  4. Undo refuses to overwrite existing paths. Contents overwritten with -o 1 cannot be recovered.
  5. Renaming the working directory or its ancestors, or moving a directory into itself, is not allowed.

Search paths:
  1. Overlapping inputs rename each source entry once; {nr} follows the first encounter.
     Empty path arguments are invalid; omit paths or use . for the current directory.
     With -w, undo records the stored spelling of explicitly named entries when available.
  2. Moves finish before directory or symlink parents used by their paths are renamed, including link chains.
     A directory moving to a new path is placed before files moving into it.
     Moves touching the same entry retain their original order. Cyclic dependencies are rejected.
  3. -l lists matching source paths without reading key-value inputs or applying replacements.
     An empty list produces no output.
  4. Fatal search or target-check errors stop the scan with exit status 1 before any files are renamed.
     The error message states when not all paths were checked; -d does not suppress these errors.

Unicode filenames:
  --unicode-nfc matches filenames in Unicode Normalization Form C (NFC). For example, it
  treats 'u' followed by a combining circumflex (U+0302) as 'û' (U+00FB). Write patterns
  and filters in NFC. A pattern such as 'août' then matches either spelling.
  Listing and undo use the original paths. Replacements use the NFC spelling of the basename,
  including captures and unmatched text. With -e, the original extension is preserved.

Three path filters:

  1. -S/--skip-filters       black list     default value: ^\. (skipping paths starting with ".")
  2. -F/--exclude-filters    black list     no default value
  3. -f/--include-filters    white list     default value: .   (anything)

  Notes:
  1. Paths starting with "." are ignored by default, disable this with -S "".
  2. These options support multiple values, e.g., -f ".html" -f ".htm".
     But ATTENTION: each comma in filters is treated as a separator of multiple filters.
     Please use double quotation marks for patterns containing comma, e.g., -f '"A{2,}"'
  3. The three filters are performed in order of -S, -F, -f.
  4. -F/--exclude-filters is prefered for excluding path, cause it has no default value.
     Setting -S/--skip-filters will overwrite its default value.
  5. Skip and exclude filters also skip matching subdirectories during recursive search.
     Include filters select entries to rename without stopping traversal. Explicit search roots are searched.

Undo and history:
  1. Successful moves are recorded even if a later move fails. Undo failures remain in the log for retry.
     Malformed records are rejected before any undo move.
  2. -U continues independent undo operations after failures and returns a nonzero status if any fail.
     Failed restores keep both paths and the directories and links needed to retry them.
  3. -d previews renaming, undo, and --clear without changing files. Rename preview checks undo log paths;
     undo preview lists recorded operations.
  4. History stays in .brename_detail.txt. Existing logs remain readable, and ordinary filenames
     retain the old record format. Logs with filenames requiring escaping need an updated build.
     Moves that invalidate their own directory alias use resolved paths in the log.
  5. Undo prepares a temporary recovery log before moving files; its directory must be writable.


Special replacement symbols:

  {nr}    Ascending integer
  {kv}    Corresponding value of the key (captured variable $n) by key-value file,
          n can be specified by flag -I/--key-capt-idx (default: 1).
          Each match uses its own key. If any key is missing, the whole filename is skipped
          unless -K/--keep-key or -m/--key-miss-repl supplies a fallback.
          -K keeps a missing key literally, including any '$' characters.

Special cases of replacement string:
 *1. Capture variables should be in the format of '${1}' to reduce errors.
    a). If the capture variable is followed with space or other simple, it's OK:
            -r '$1 abc'
    b). If followed by numbers, characters, or underscore. That is ambiguous:
            -r '$1abc' actually refers to the variable '1abc', please use '${1}abc'.
            -r '$2_$1' actually refers to the variable '2_', please use '${2}_${1}'.
  2. Want to replace with a charactor '$',
    a). If using '{kv}', you need use '$$$$' instead of a single '$':
            -r '{kv}' -k <(sed 's/\$/$$$$/' kv.txt)
    b). If not, use '$$'. e.g., adding '$' to all numbers:
            -p '(\d+)' -d -r '$$${1}'

Usage:
  brename [flags]

Examples:
  1. dry run and showing potential dangerous operations (-d)
      brename -p "abc" -d
  2. dry run and only show operations that will cause error (-v)
      brename -p "abc" -d -v 2
  3. only renaming specific paths via include filters (-f)
      brename -p ":" -r "-" -f ".htm$" -f ".html$"
  4. renaming all .jpeg files to .jpg in all subdirectories (-R)
      brename -p "\.jpeg" -r ".jpg" -R   dir
  5. using capture variables, e.g., $1, $2 ...
      brename -p "(a)" -r "\$1\$1"
      or brename -p "(a)" -r '$1$1' in Linux/Mac OS X
  6. renaming directory too (-D)
      brename -p ":" -r "-" -R -D   pdf-dirs
  7. using key-value file (-k)
      brename -p "(.+)" -r "{kv}" -k kv.tsv
  8. do not touch file extension (-e)
      brename -p ".+" -r "{nr}" -f .mkv -f .mp4 -e
  9. only list paths that match pattern (-l)
      brename -i -f '.docx?$' -p . -R -l
  10. undo the last rename operation; retain failed entries for retry (-u)
      brename -u
  11. disable undo if you do not want to create .brename_detail.txt (-x)
      brename -p xxx -r yyy -x
  12. clear/remove all .brename_detail.txt files (--clear)
      brename --clear -R
  13. also operate on hidden files: empty -S (default: ^\.)
      brename -p xxx -r yyy -S ""

  More examples: https://github.com/shenwei356/brename

Flags:
  -w, --case-insensitive-path     the file system (e.g., FAT32 or NTFS) is case-insensitive. It's
                                  automatically swiched on on Windows
  -W, --case-sensitive-path       believing that the file system is case-sensitive. Please use this to
                                  disable the flag -w/--case-insensitive-path, which is switched on by
                                  default on Windows
      --clear                     remove .brename_detail.txt files; use -R/--recursive to include
                                  subdirectories
  -x, --disable-undo              do not create .brename_detail.txt file for undo
  -d, --dry-run                   preview rename, undo, or history removal without changing files
  -F, --exclude-filters strings   exclude file filter(s) (regular expression, NOT wildcard). multiple
                                  values supported, e.g., -F ".html" -F ".htm", but ATTENTION: each
                                  comma in the filter is treated as the separator of multiple filters,
                                  please use double quotation marks for patterns containing comma, e.g.,
                                  -F '"A{2,}"'
  -U, --force-undo                continue undo after failures without overwriting existing paths
  -h, --help                      help for brename
  -i, --ignore-case               ignore case in the search pattern, path filters and key-value lookup
  -E, --ignore-err                ignore directory reading errors
  -e, --ignore-ext                ignore file extension. i.e., replacement does not change file extension
  -f, --include-filters strings   include file filter(s) (regular expression, NOT wildcard). multiple
                                  values supported, e.g., -f ".html" -f ".htm", but ATTENTION: each
                                  comma in the filter is treated as the separator of multiple filters,
                                  please use double quotation marks for patterns containing comma, e.g.,
                                  -f '"A{2,}"' (default [.])
  -D, --including-dir             rename directories
  -K, --keep-key                  keep the key as value when no value found for the key
  -I, --key-capt-idx int          capture variable index of key (1-based) (default 1)
  -m, --key-miss-repl string      replacement for key with no corresponding value
  -k, --kv-file string            tab-delimited key-value file for replacing key with value when using
                                  "{kv}" in -r (--replacement)
  -l, --list                      only list paths that match pattern, without planning renames
  -a, --list-abs                  list absolute path, using along with -l/--list
  -s, --list-sep string           separator for list of found paths (default "\n")
      --max-depth int             maximum depth for recursive search or --clear (0 for no limit)
  -N, --nature-sort               sort digit runs numerically when renaming or listing
      --nr-width int              minimum width for {nr} (1-1000000). e.g., format "1" as "001" with
                                  --nr-width 3 (default 1)
      --only-dir                  only rename directories
  -o, --overwrite-mode int        overwrite mode (0 for reporting error, 1 for overwrite, 2 for not
                                  renaming) (default 0)
  -p, --pattern string            search pattern (regular expression)
  -q, --quiet                     be quiet, do not show any information and warning
  -R, --recursive                 rename recursively
  -r, --replacement string        replacement. capture variables supported.  e.g. $1 or ${1} (prefered)
                                  represents the first submatch. ATTENTION: for *nix OS, use SINGLE
                                  quote NOT double quotes or use the \ escape character. Ascending
                                  integer is also supported by "{nr}"
  -S, --skip-filters strings      skip file filter(s) (regular expression, NOT wildcard). multiple
                                  values supported, e.g., -S "^\." for skipping files starting with a
                                  dot, but ATTENTION: each comma in the filter is treated as the
                                  separator of multiple filters, please use double quotation marks for
                                  patterns containing comma, e.g., -S '"A{2,}"' (default [^\.])
  -n, --start-num int             starting number when using {nr} in replacement (default 1)
  -u, --undo                      undo the last rename operation; retain failed entries for retry
      --unicode-nfc               match filenames in Unicode Normalization Form C (NFC)
  -v, --verbose int               verbose level (0 for all, 1 for warning, error and renamed files, 2
                                  for only error and renamed files) (default 2)
  -V, --version                   print version information and check for update

Examples

Take this directory as an example (run generate-example-folder.sh to generate it):

$ sh generate-example-folder.sh 
example
├── abc
│   ├── A.JPEG
│   ├── B.HTM
│   └── B.JPEG
├── a.html
├── a.jpeg
└── b.jpeg

# examples below were executed in directory: example
cd example/
  1. Recursively renaming all .jpeg files to .jpg in all subdirectories (-R/--recursive). A dry run is performed first to check for errors (-d/--dry-run).

     $ brename -p "\.jpeg" -r ".jpg" -R -d
     Searching for paths to rename...
    
       [OK] example/a.jpeg -> example/a.jpg
       [OK] example/b.jpeg -> example/b.jpg
    
     2 path(s) to be renamed
    
    
     $ brename -p "\.jpeg" -r ".jpg" -R
     Searching for paths to rename...
    
       Done searching.
    
     Renaming paths...
    
       [DONE] example/a.jpeg -> example/a.jpg
       [DONE] example/b.jpeg -> example/b.jpg
    
     2 path(s) renamed in 0.001 seconds
    
     $ tree
     .
     ├── abc
     │   ├── A.JPEG
     │   ├── B.HTM
     │   └── B.JPEG
     ├── a.html
     ├── a.jpg
     └── b.jpg
    
  2. Undo the last rename operation (-u/--undo, -U/--force-undo)

     $ brename -u
     Renaming paths back...
    
       [DONE] example/b.jpg -> example/b.jpeg
       [DONE] example/a.jpg -> example/a.jpeg
    
     2 path(s) renamed back in 0.000 seconds
    

    Undo refuses to overwrite files created at their old names. If an operation fails, its record remains in the log so you can resolve the conflict and retry. -U continues independent operations after failures and returns a nonzero exit status if any operation fails. Dependent paths are skipped even through directory symlinks. It does not enable overwriting.

    Use brename -u -d to list recorded undo operations without changing files. brename --clear -d -R previews history removal. Undo cannot recover contents overwritten with -o 1.

    History remains in .brename_detail.txt. Existing logs are still readable, and ordinary filenames retain the old record format, which older versions can read. Only logs containing filenames that need escaping use a versioned format; these require an updated build. Temporary writes use .brename_detail.txt.tmp-* in the current working directory, beside .brename_detail.txt, and replace the history file only after writing succeeds.

    Undo prepares a complete temporary recovery log before moving files, then reuses it for any remaining records. If this preparation fails, no files are moved. The history directory must be writable and have room for the temporary log.

    Undo logs must be regular files and must not alias files being renamed. With undo enabled, targets cannot use .brename_detail.txt as a directory. Do not run concurrent rename operations against the same paths or history file.

    Disable undo if you do not want to create .brename_detail.txt (-x)

     $ brename -p xxx -r yyy -x
    

    Clear/remove all .brename_detail.txt files (--clear)

     $ brename --clear -R
    
  3. Dry run, only showing operations that will cause errors (remove -d to rename).

     # default value of -v is 2
     $ brename -p a -r b -R -D -d
     Searching for paths to rename...
    
       [OK] a.html -> b.html
       [new path existed] a.jpeg -> b.jpeg
       [OK] abc -> bbc
    
     1 potential error(s) detected, please check
    
     $ brename -p a -r b -R -D
     Searching for paths to rename...
    
       Done searching.
       [new path existed] example/a.jpeg -> example/b.jpeg
    
     1 potential error(s) detected, please check
    
  4. Ignoring cases (-i/--ignore-case)

     $ brename -p "\.jpeg" -r ".jpg" -R -i
     Searching for paths to rename...
    
       Done searching.
    
     Renaming paths...
    
       [DONE] abc/A.JPEG -> abc/A.jpg
       [DONE] abc/B.JPEG -> abc/B.jpg
    
     2 path(s) renamed in 0.000 seconds
    
    
     $ tree
     .
     ├── abc
     │   ├── A.jpg
     │   ├── B.HTM
     │   └── B.jpg
     ├── a.html
     ├── a.jpg
     └── b.jpg
    
  5. Using capture variables, e.g., $1, $2 ...

     # or brename -p "(a)" -r '$1$1' in Linux/Mac OS X
     $ brename -p "(a)" -r "\$1\$1" -i
     Searching for paths to rename...
    
       Done searching.
    
     Renaming paths...
    
       [DONE] a.html -> aa.html
       [DONE] a.jpg -> aa.jpg
    
     2 path(s) renamed in 0.000 seconds
    
     $ tree
     .
     ├── aa.html
     ├── aa.jpg
     ├── abc
     │   ├── A.jpg
     │   ├── B.HTM
     │   └── B.jpg
     └── b.jpg
    
  6. Renaming directories too (-D/--including-dir), or renaming directories only (-D --only-dir)

     $ brename -p "a" -r "A" -R -D
     Searching for paths to rename...
    
       Done searching.
    
     Renaming paths...
    
       [DONE] aa.html -> AA.html
       [DONE] aa.jpg -> AA.jpg
       [DONE] abc -> Abc
    
     3 path(s) renamed in 0.001 seconds
    
     $ tree
     .
     ├── AA.html
     ├── AA.jpg
     ├── Abc
     │   ├── A.jpg
     │   ├── B.HTM
     │   └── B.jpg
     └── b.jpg
    
  7. Only renaming specific files via include filters (regular expression) (-f/--include-filters)

     $ brename -p '(.)' -r ' $1' -d
     Searching for paths to rename...
    
       [OK] AA.html ->  A A . h t m l
       [OK] AA.jpg ->  A A . j p g
       [OK] b.jpg ->  b . j p g
    
     3 path(s) to be renamed
    
    
     
     $ brename -p '(.)' -r ' $1' -d -f '\.jpg$'
     Searching for paths to rename...
    
       [OK] AA.jpg ->  A A . j p g
       [OK] b.jpg ->  b . j p g
    
     2 path(s) to be renamed
    

    Attention: values of -f/--include-filters and -F/--exclude-filters should be regular expressions, NOT wildcards!

     $ brename -p '(.)' -r '$1 ' -d -f *.jpg
     Seems you are using wildcard for -f/--include-filters? Make sure using regular expression: AA.jpg
     Searching for paths to rename...
    
    
     0 path(s) to be renamed
     
     $ brename -p '(.)' -r '$1 ' -d -f '*.jpg'
     Are you using wildcard for -f/--include-filters? It should be regular expression: *.jpg
     illegal regular expression for include filter: *.jpg
     
     $ brename -p '(.)' -r '$1 ' -d -f A*
     Seems you are using wildcard for -f/--include-filters? Make sure using regular expression: AA.html
     Searching for paths to rename...
    
    
     0 path(s) to be renamed
    
  8. Excluding files via exclude filters (regular expression) (-F/--exclude-filters)

     $ brename -p '(.)' -r ' $1' -d
     Searching for paths to rename...
    
       [OK] AA.html ->  A A . h t m l
       [OK] AA.jpg ->  A A . j p g
       [OK] b.jpg ->  b . j p g
    
     3 path(s) to be renamed
    
    
     $ brename -p '(.)' -r ' $1' -d -F '\.html$'
     Searching for paths to rename...
    
       [OK] AA.jpg ->  A A . j p g
       [OK] b.jpg ->  b . j p g
    
     2 path(s) to be renamed
     
    
  9. Skipping files via skip filter (regular expression) (-S/--skip-filters). This filter step is performed before the exclude filters. The default value ^\. is for skipping files starting with a dot, which are hidden files in Linux. Matching subdirectories are also skipped during recursive search, even without -D. Include filters select files and directories to rename without pruning subdirectories. Explicit search roots are searched. If you do not want to skip hidden entries, just empty it.

     $ brename -p xxx -r yyy -S ""
    
  10. Do not touch file extension (-e/--ignore-ext)

     $ brename -p '(.)' -r ' $1' -d
     Searching for paths to rename...
    
       [OK] AA.html ->  A A . h t m l
       [OK] AA.jpg ->  A A . j p g
       [OK] b.jpg ->  b . j p g
    
     3 path(s) to be renamed
    
     $ brename -p '(.)' -r ' $1' -d -e
     Searching for paths to rename...
    
       [OK] AA.html ->  A A.html
       [OK] AA.jpg ->  A A.jpg
       [OK] b.jpg ->  b.jpg
    
     3 path(s) to be renamed
    
  11. Renaming with numbers (-r "{nr}")

     $ brename -d -p '(.+)\.' -r 'pic-{nr}.' -f .jpg -d
     Searching for paths to rename...
    
       [OK] AA.jpg -> pic-1.jpg
       [OK] b.jpg -> pic-2.jpg
    
     2 path(s) to be renamed
    
    
     $ brename -d -p '(.+)\.' -r 'pic-{nr}.' -f .jpg -d --nr-width 3 --start-num 11
     Searching for paths to rename...
    
       [OK] AA.jpg -> pic-011.jpg
       [OK] b.jpg -> pic-012.jpg
    
     2 path(s) to be renamed
    
  12. Replace submatches with corresponding values via a tab-delimited key-value file (-k/--kv-file)

    Each match uses its own captured key. For example, with a mapped to Alpha and b mapped to Beta, -p '([ab])' -r '{kv}' -k kv.tsv renames a-b to Alpha-Beta. If any key is missing, the whole filename is skipped unless -K or -m supplies a fallback.

     $ more kv.tsv
     a       一
     b       二
     c       三
    
     $ brename -p '^(\w)' -r '{kv}' -k kv.tsv -K -i -d
     read key-value file: kv.tsv
     3 pairs of key-value loaded
     Searching for paths to rename...
    
       [OK] AA.html -> 一A.html
       [OK] AA.jpg -> 一A.jpg
       [OK] b.jpg -> 二.jpg
       [unchanged] kv.tsv -> kv.tsv
    
     3 path(s) to be renamed
    
  13. Auto mkdir

     $ touch a-b-c.txt
    
     $ brename -f .txt -p '-' -r '/'
     Searching for paths to rename...
    
       Done searching.
    
     Renaming paths...
    
       [DONE] a-b-c.txt -> a/b/c.txt
    
     1 path(s) renamed in 0.000 seconds
    
     $ tree a
     a
     └── b
         └── c.txt
    
  14. Only listing paths that match pattern (-l and -a)

     $ brename -p '.gz$' -R -l
     binaries/brename_darwin_386.tar.gz
     binaries/brename_darwin_amd64.tar.gz
     binaries/brename_linux_386.tar.gz
     binaries/brename_linux_amd64.tar.gz
     binaries/brename_windows_386.exe.tar.gz
     binaries/brename_windows_amd64.exe.tar.gz
    
     $ brename -p '.gz$' -R -l -a
     /home/shenwei/project/src/github.com/shenwei356/brename/binaries/brename_darwin_386.tar.gz
     /home/shenwei/project/src/github.com/shenwei356/brename/binaries/brename_darwin_amd64.tar.gz
     /home/shenwei/project/src/github.com/shenwei356/brename/binaries/brename_linux_386.tar.gz
     /home/shenwei/project/src/github.com/shenwei356/brename/binaries/brename_linux_amd64.tar.gz
     /home/shenwei/project/src/github.com/shenwei356/brename/binaries/brename_windows_386.exe.tar.gz
     /home/shenwei/project/src/github.com/shenwei356/brename/binaries/brename_windows_amd64.exe.tar.gz
    
  15. Overwrite mode (-o/--overwrite-mode)

     $ ls *.tar.gz
     brename_darwin_386.tar.gz    brename_linux_386.tar.gz    brename_windows_386.exe.tar.gz
     brename_darwin_amd64.tar.gz  brename_linux_amd64.tar.gz  brename_windows_amd64.exe.tar.gz
    
    1. default mode: reporting error

       $ brename -p 386 -r amd64 -d
       Searching for paths to rename...
      
         [new path existed] brename_linux_386.tar.gz -> brename_linux_amd64.tar.gz
         [new path existed] brename_windows_386.exe.tar.gz -> brename_windows_amd64.exe.tar.gz
      
       2 potential error(s) detected, please check
      
    2. allowing overwrite

       $ brename -p 386 -r amd64 -d -o 1
       Searching for paths to rename...
      
         [new path existed] brename_linux_386.tar.gz -> brename_linux_amd64.tar.gz (will be overwritten)
         [new path existed] brename_windows_386.exe.tar.gz -> brename_windows_amd64.exe.tar.gz (will be overwritten)
      
       2 path(s) to be renamed
      
    3. leave it

       $ brename -p 386 -r amd64 -d -o 2
       Searching for paths to rename...
      
         [new path existed] brename_linux_386.tar.gz -> brename_linux_amd64.tar.gz (will NOT be overwritten)
         [new path existed] brename_windows_386.exe.tar.gz -> brename_windows_amd64.exe.tar.gz (will NOT be overwritten)
      
       0 path(s) to be renamed
      

Real-world examples

  1. Formatting a genome assembly filename from NCBI.

     $ ls 
     GCF_029211165.1_ASM2921116v1_genomic.fa
    
     # ------------------------------------------------------------------------
     # only keeping accession
    
     Searching for paths to rename...
    
     [OK] GCF_029211165.1_ASM2921116v1_genomic.fa -> GCF_029211165.fa
    
     1 path(s) to be renamed
    
     # ------------------------------------------------------------------------
     # keeping accession.version
     
     $ brename -R -p '^(\w{3}_\d{9}\.\d+).+' -r '$1.fa' -d
     Searching for paths to rename...
    
       [OK] GCF_029211165.1_ASM2921116v1_genomic.fa -> GCF_029211165.1.fa
    
     1 path(s) to be renamed
    
  2. Replace matches with corresponding pairing values

    1. Original files

       $ tree
       .
       ├── barcodes.tsv
       ├── tag_ATGCGTA.fasta
       ├── tag_CCCCCCC.fasta
       ├── tag_CGACGTC.fasta
       ├── tag_TCATAGC.fasta
       └── tag_TCTATAG.fasta
      
    2. Tab-delimited key-value file. Notice that CCCCCCC is not in it.

       $ cat barcodes.tsv
       CGACGTC S1
       ATGCGTA S2
       TCTATAG S4
       TCATAGC S3
      
    3. Renaming tags as sample names, using unknown for missing tags.

       $ brename -e -p 'tag_(\w+)' -r '{kv}' -k barcodes.tsv -m unknown -d
       [INFO] read key-value file: barcodes.tsv
       [INFO] 4 pairs of key-value loaded
       [INFO] checking: [ ok ] 'tag_ATGCGTA.fasta' -> 'S2.fasta'
       [INFO] checking: [ ok ] 'tag_CCCCCCC.fasta' -> 'unknown.fasta'
       [INFO] checking: [ ok ] 'tag_CGACGTC.fasta' -> 'S1.fasta'
       [INFO] checking: [ ok ] 'tag_TCATAGC.fasta' -> 'S3.fasta'
       [INFO] checking: [ ok ] 'tag_TCTATAG.fasta' -> 'S4.fasta'
       [INFO] 5 path(s) to be renamed
      
  3. Renaming PDF files for compatibility (moving from EXT4 to NTFS file system):

    1. Original files

       $ tree -Q
       .
       ├── "0000 Test.pdf"
       ├── "2016 SeqKit: A Cross-Platform and Ultrafast Toolkit for FASTA\342\201\204Q File Manipulation .pdf"
       ├── "metagenomics"
       │   ├── "2017 16S rRNA gene sequencing and healthy reference ranges for 28 clinically relevant microbial taxa from the human gut microbiome .pdf"
       │   ├── "2017 De novo assembly of viral quasispecies using overlap graphs .pdf"
       │   └── "2017 Tracking microbial colonization in fecal microbiota transplantation experiments via genome-resolved metagenomics .pdf"
       ├── "test2222222222222222222211111111122222222222222222233333333.pdf"
       └── "test.pdf"
      
    2. Removing "\n", "'", "?".

       $ brename -p "[\n'\?]" -r " " -R
       
      
    3. Replacing ":" with " _"

       $ brename -p ":" -r " _" -R
      
    4. Shortening file names (preferring to split at a space)

       $ brename -R -f .pdf -i -p "^(.{30,50})[ \.].*.pdf" -r "\$1.pdf" -d
      
    5. Result

       $ tree -Q
       .
       ├── "0000 Test.pdf"
       ├── "2016 SeqKit _ A Cross-Platform and Ultrafast.pdf"
       ├── "metagenomics"
       │   ├── "2017 16S rRNA gene sequencing and healthy.pdf"
       │   ├── "2017 De novo assembly of viral quasispecies using.pdf"
       │   └── "2017 Tracking microbial colonization in fecal.pdf"
       ├── "test2222222222222222222211111111122222222222222222233333333.pdf"
       └── "test.pdf"
      

FAQs

Contact

Create an issue to report bugs, propose new features or ask for help.

License

MIT License

관련 프로젝트 살펴보기

불러오는 중…