0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

bashのブレース展開

Last updated at Posted at 2024-12-22

ブレース展開とは?

ブレース展開は、{} で囲まれたパターンを、指定された文字列の組み合わせに展開する機能です。

例えば、以下のようなパターンがあるとします。

echo {a,b,c}-{1,2,3}.txt

これは次のように展開されます。

a-1.txt a-2.txt a-3.txt b-1.txt b-2.txt b-3.txt c-1.txt c-2.txt c-3.txt

このように、{} 内のカンマ区切りの文字列と、その前後の文字列を組み合わせて、複数の文字列を生成できます。

基本的な書式

ブレース展開の基本的な書式は以下の通りです。

{文字列1,文字列2,...,文字列N}
{<始まり>..<終わり>}
{<始まり>..<終わり>..<インクリメント>}  # Bash 4 以降
<頭に付けたい文字列>{........}
{........}<後尾に付けたい文字列>
<頭に付けたい文字列>{........}<後尾に付けたい文字列>
{文字列1,文字列2}{文字列3,文字列4}
{,文字列1,文字列2}
<文字列0>{文字列1,,,文字列2}
<文字列>{,,,}

使用例

1. カンマ区切りの文字列展開

$ echo {a,b}.txt
a.txt b.txt

$ echo {a,b,c}-{1,2,3}.txt
a-1.txt a-2.txt a-3.txt b-1.txt b-2.txt b-3.txt c-1.txt c-2.txt c-3.txt

2. 連番の生成

$ echo {1..5}
1 2 3 4 5

$ echo {a..e}
a b c d e

$ echo {1..10..2} # 1から10まで2ずつ増やす
1 3 5 7 9

$ echo {a..z..5} # aからzまで5つ飛ばし
a f k p u z

3. ファイル名の生成

$ mv file.{txt,bak} # file.txt を file.bak にリネーム

4. ディレクトリの一括作成

$ mkdir dir{1,2,3} # dir1, dir2, dir3 を作成

5. ループ処理

$ for i in {1..5}; do echo "Number: $i"; done
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

6. 変数と組み合わせた利用

$ PREFIX=image
$ echo ${PREFIX}_{a,b,c}.jpg
image_a.jpg image_b.jpg image_c.jpg

参考記事

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?