Linuxを使用していて、特定の文字列を含むファイルを検索したいことがあると思います。
今回は、そのような特定の文字列を含むファイルを検索する方法について紹介します。
Contents
ファイル名に「○○」という文字列が含まれているファイルのリストを取得する。
ls [検索対象フォルダのパス] | grep "[検索したい文字列]" #例 [vagrant@localhost conf]$ ls ./ | grep 'httpd' httpd.conf
find [検索対象フォルダのパス] -type f -name '*[検索したい文字列]*' #例 [vagrant@localhost httpd]$ find ./ -type f -name '*httpd*' ./conf/httpd.conf
ファイルを開いた中身に、「○○」という文字列が含まれているファイルのリスト
grepを使用した方法
grep [検索したい文字列] -r [検索対象フォルダのパス] #例 [vagrant@localhost httpd]$ grep 'server' -r ./ ./conf/httpd.conf:# This is the main Apache HTTP server configuration file. It contains the ./conf/httpd.conf:# configuration directives that give the server its instructions. ...
findを使用する方法
find [検索対象フォルダのパス] -type f -print | xargs grep '[検索したい文字列]' #例 [vagrant@localhost httpd]$ find ./ -type f -print | xargs grep 'server' ./conf/httpd.conf:# This is the main Apache HTTP server configuration file. It contains the ./conf/httpd.conf:# configuration directives that give the server its instructions. ...
find のオプションは、以下のような意味です。
-type f | このoptionでは検索するタイプを指定します。 今回は「f」としているので通常ファイルが対象になります。 |
検索結果を標準出力します |
指定の用語を含むファイル名を検索する方法、ファイル内に指定の用語を含む検索の方法について紹介しました。
Linuxをいじっているとどちらも必要になる知識だと思います。