ひゃまだのblog

ひゃまだ(id:hymd3a)の趣味のブログ

Bashの便利なブレース展開(Brace Expansion)

(2024-02-08 初稿 )

 Bashにはブレース展開と呼ばれる便利な機能がある。

このページでは、以下のサイトを参考に作った筆者の備忘録である。

基本編

まずは、ブレース展開の基本的な機能の抜粋について記述する。

echo {a,b,c}   → a b c
echo {a..c}    → a b c
echo {0..4}  → 0 1 2 3 4  # 小さい順
echo {4..0}  → 4 3 2 1 0  # 大きい順

Bash ver4.0 以降は増減を指定できる。

echo {0..4..2} → 0 2 4

ブレース展開は組合せもできる。

筆者は、この組合せを多様するので、本当に助かる。

$ echo {a..b}{0..3} →< a0 a1 a2 a3 b0 b1 b2 b3

前後に文字をつける

$ echo a{b,c,d}e  → abe ace ade

「,」(カンマ)は、前後の文字

$ echo a{,b,c,d}e  → ae abe ace ade

日本語でも可

$ echo 山{,田}の  → 山の 山田の

応用編

深いディレクトリのファイルのバックアップ

$ mv /lpath/longpath/longlongpath/longlonglongpath/config{,.bak}
$ ls lpath/longpath/longlongpath/longlonglongpath/config*
config config.bak

ファイルの一括作成

$ touch test{0..5}
$ ls test*
test0  test1  test2  test3  test4  test5

一括ファイル名変更

$ for f in test*; { mv $f{,.txt}; }
$ ls test*
test0.txt  test1.txt  test2.txt  test3.txt  test4.txt  test5.txt

for文の条件

$ for i in {1..5}; { echo $i; }
1
2
3
4
5

ざっと簡単に紹介したが、本当にbashだけでできることが多くて助かる。

皆さんの少しでも参考になれば幸い。

また、何か気がついたら追記する。

 

関連ページ