awkコマンドってなに?
「awk」は空白やカンマなどで区切られたテキストを処理するコマンド
基本構文
awk 'パターン {アクション}' ファイル名
- パターン:そり対象となる行を選択する条件
- アクション:マッチした行に対して実行する処理内容
オプション
オプション | 説明 |
---|---|
-F |
フィールド(列)の区切り文字を指定する |
-v |
変数をコマンドラインから指定する |
-f |
AWKスクリプトをファイルから読み込んで実行する |
-W |
特定の警告オプションを有効にする |
例
パターン1
sample.txt
apple orange banana
cat dog mouse
one two three
awkコマンド
awk '{print $1}' sample.txt
各行に対して一番目のフィールド(列)を出力する
結果
apple
cat
one
パターン2
date.txt
A 20 45
B 15 50
C 30 55
D 10 30
awkコマンド
awk '$3 >= 50 { print $1, $3 }' data.txt
data.txtの3列目の値が50以上の行の1列目と3列目を表示
結果
B 50
C 55
おまけ(gawkってなに?)
GNUプロジェクトが開発したAWKの拡張バージョンでawkの全機能に加えて追加の拡張機能のを使用できる