LoginSignup
6
6

More than 5 years have passed since last update.

ディレクトリ内の一番大きな番号につづくように番号を振ってファイル名を生成する

Posted at

表題のような場面にはよく出くわすかと思います。

なので,zshプラグインにしました。

使い方

path
└── to
    └── save
        ├── 01_file
        ├── 02_file
        ├── 04_file
        ├── file_001.txt
        ├── file_002.txt
        └── file_003.txt

のようにディレクトリとファイルがあったときに,ディレクトリ名とマッチパターンを渡すことでそのディレクトリ内で一番大きな番号+1したファイル名を返す関数get_serialised_filenameです。

たとえば

$ echo "$(get_serialised_filename -d "/path/to/save" -b "file_" -e "txt")"
/path/to/save/file_004.txt

$ echo "$(get_serialised_filename -d "/path/to/save" -n 2 -a "_file")"
/path/to/save/05_file

のようになります。

存在しないディレクトリを指定した場合でもエラーを出さず,

$ echo "$(get_serialised_filename -d "/path/to/other" -b "newfile_" -e "md")"
/path/to/other/newfile_001.md

となります。

オプションは,例をみてもらえれば分かるように,

Options Arguments
-b filename_before
-a filename_after
-e filename_extension
-d root_dir
-n num_of_digits

のようになっています。

インストール方法

zshプラグインマネージャを使用する方法

インストールは、zshプラグインマネージャ(zplug,zgen,antigenなど)からでもできます。

zshrcに:

antigen

antigen bundle ssh0/zsh-get_serialised_filename

zgen

zgen load ssh0/zsh-get_serialised_filename

zplug

zplug "ssh0/zsh-get_serialised_filename"

手動でインストールする

手動でインストールするのも簡単です。
ちなみにzshプラグインと言っていますが、bashでもdashでも使用することができます。

1: GitHubから(適当な場所に)クローンする

git clone https://github.com/ssh0/zsh-get_serialised_filename.git ~/.zsh/plugins/zsh-get_serialised_filename

2: zshrc(もしくはbashrc)でsourceする。

source $HOME/.zsh/plugins/zsh-get_serialised_filename/get_serialised_filename.sh

dashではsourceコマンドが使えないので、

. $HOME/.zsh/plugins/zsh-get_serialised_filename/get_serialised_filename.sh

のようにすれば使えます。

まとめ

メモ取り用、ログ管理、スクリーンショット、その他決められたディレクトリ内に連番でファイルを保存していくという用途は多くあると思うので、活用してみてください。

6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6