0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

grepでワイルドカードがうまく動かない理由と正しい使い方まとめ

0
Posted at

LinuxやmacOSのターミナルで grep *2024* と打ったら、
「Is a directory」というエラーが出たことはありませんか?

kubota_akihiro:test_directories $ ls -l | grep *2024*
grep: test20240326: Is a directory
grep: test20240330: Is a directory
grep: test20240908: Is a directory

この記事では、なぜこのエラーが出るのか? そして、どうすれば意図通りに「2024を含む行だけ」を抽出できるのか? を解説します。

🔍 結論:2024 はシェルが展開してしまう!

grep *2024*

このように書くと、2024 は grep に渡る前に シェル(bashやzsh)が展開してしまいます。

例:展開されるとこうなる

grep test20240326 test20240330 test20240908

つまり、grep は「2024という文字列を検索する」のではなく、 「test20240326というファイルを開いて中身を検索しよう」としているのです。

その結果、ディレクトリを開こうとしてエラーになります。

✅ 正しい書き方:クォートで囲む!

ls -l | grep '2024'

これで ls -l の出力の中から「2024」を含む行だけを抽出できます。

📌 なぜ '2024' とクォートするの?
クォートすることで、シェルによるワイルドカード展開を防ぐ

grep に「文字列としての2024」を渡すことができる

🧪 実例:ディレクトリ一覧から2024を含む行だけ抽出

kubota_akihiro:test_directories $ ls -l
total 0
drwxr-xr-x  29 kubota_akihiro  staff  928  6  4 23:21 temp20220625
drwxr-xr-x   9 kubota_akihiro  staff  288  1 28  2024 test20211114
drwxr-xr-x  10 kubota_akihiro  staff  320  5  7  2023 test20221217
drwxr-xr-x  14 kubota_akihiro  staff  448  2 20 23:43 test20231113
drwxr-xr-x   6 kubota_akihiro  staff  192  3  8 19:43 test20240308
drwxr-xr-x   7 kubota_akihiro  staff  224  5 26  2024 test20240326
drwxr-xr-x   7 kubota_akihiro  staff  224  5 15  2024 test20240330
drwxr-xr-x   4 kubota_akihiro  staff  128  6 23 14:18 test20240908
kubota_akihiro:test_directories $ ls -l | grep '2024'
drwxr-xr-x   9 kubota_akihiro  staff  288  1 28  2024 test20211114
drwxr-xr-x   6 kubota_akihiro  staff  192  3  8 19:43 test20240308
drwxr-xr-x   7 kubota_akihiro  staff  224  5 26  2024 test20240326
drwxr-xr-x   7 kubota_akihiro  staff  224  5 15  2024 test20240330
drwxr-xr-x   4 kubota_akihiro  staff  128  6 23 14:18 test20240908
0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?