Linux の検索とテキスト加工技術
概要
Linux の検索・テキスト加工技術は、システム管理、開発、ログ解析などのさまざまな場面で重要な役割を果たします。
ログファイルには情報やエラーメッセージが記録されます。検索とテキスト加工技術を利用することで、ログファイルから特定のエラーやイベントを抽出し、トラブルシューティングや問題解決に活用できます。
実践
文字列を特定の区切り文字で分割する
cut コマンドでは、-d で区切り文字を指定し、-f で取得する列番号を指定します。
$ cat file.txt
No,hostname,ip,description
1,web01,172.16.0.50,web server
3,db01,172.16.0.60,db server
4,adsv01,172.16.0.61,ActiveDirectory
5,adsv02,172.16.0.62,ActiveDirectory
3列目(IPアドレス)を取得します。
$ cat file.txt | cut -d ',' -f 3
ip
172.16.0.50
172.16.0.60
172.16.0.61
172.16.0.62
特定文字列を出現回数でカウントする
grep -o で一致した文字列のみを出力し、sort と uniq -c で件数を集計します。
$ cat file.txt
apple banana apple orange
$ grep -o "apple" file.txt | sort | uniq -c
2 apple
上記の例では、apple が2つ含まれていることが分かります。
特定文字列を含む行数をカウントする
$ cat file.txt
apple banana apple orange
$ grep -c "apple" file.txt
1
grep -cは文字列の出現回数ではなく、指定した文字列を含む行数をカウントします。
文字列を置換する
sed を使用して文字列を置換します。
$ cat file.txt
apple banana apple orange
$ sed 's/apple/google/g' file.txt
google banana google orange
この結果を別ファイルにリダイレクトすれば、元のファイルを変更せずに置換後のテキストを作成できます。
sed 's/apple/google/g' file.txt > output.txt
元のファイルを直接変更する場合は、-i オプションを使用します。
sed -i 's/apple/google/g' file.txt
指定した行番号の範囲を取得する
$ cat file.txt
1
2
3
4
5
2行目から4行目までを取得します。
$ sed -n '2,4p' file.txt
2
3
4
特定の文字列を含む行を除外する
grep -v を使用すると、指定文字列に一致する行を除外できます。
$ cat file.txt
banana
apple
orange
apple
tomato
lemon
$ grep -v "apple" file.txt
banana
orange
tomato
lemon
OR 条件で文字列を検索する
grep -E と | を利用すると、いずれかの文字列に一致する行を検索できます。
$ cat file.txt
banana
apple
orange
apple
tomato
lemon
$ grep -E "banana|apple" file.txt
banana
apple
apple
AND 条件で文字列を検索する
複数の grep をパイプでつなぐことで、両方の文字列に一致する行を検索できます。
$ cat file.txt
banana
apple
banana apple
apple banana
banana orange
apple orange
$ grep "apple" file.txt | grep "banana"
banana apple
apple banana
アルファベット順に並び替える
sort コマンドを使用します。
$ cat file.txt
banana
apple
orange
apple
lemon
$ sort file.txt
apple
apple
banana
lemon
orange
指定サイズの範囲内にあるファイルを検索する
$ ls -lh
total 111M
-rw-rw-r-- 1 kamizato kamizato 96M 4月 27 18:58 100MB
-rw-rw-r-- 1 kamizato kamizato 9.6M 4月 27 18:56 10MB
-rw-rw-r-- 1 kamizato kamizato 977K 4月 27 18:56 1MB
-rw-rw-r-- 1 kamizato kamizato 4.8M 4月 27 18:56 5MB
2MBより大きく、20MBより小さい通常ファイルを検索します。
$ find ./ -type f -size +2M -size -20M
./5MB
./10MB
ファイル名で検索する
find コマンドの -name オプションでファイル名を指定して検索できます。ディレクトリを検索する場合は -type d を使用します。
$ ls -lh
total 111M
-rw-rw-r-- 1 quinaeng quinaeng 96M 4月 27 18:58 100MB
-rw-rw-r-- 1 quinaeng quinaeng 9.6M 4月 27 18:56 10MB
-rw-rw-r-- 1 quinaeng quinaeng 977K 4月 27 18:56 1MB
-rw-rw-r-- 1 quinaeng quinaeng 4.8M 4月 27 18:56 5MB
$ find ./ -type f -iname 10MB
./10MB
-iname は、大文字・小文字を区別せずにファイル名を検索します。