Linux/UnixにおけるAWKコマンド
AWKはパターン検索や処理に適しています。スクリプトは1つまたは複数のファイルを検索して、一致するパターンを特定し、そのパターンに対して特定のタスクを行います。このガイドでは、AWK Linuxコマンドについて調べ、その機能を見ていきます。
AWKはどんな操作ができますか?(AWK wa donna sōsa ga dekimasu ka?)
- Scanning files line by line
- Splitting each input line into fields
- Comparing input lines and fields to patterns
- Performing specified actions on matching lines
AWKコマンドの有用性
- Changing data files
- Producing formatted reports
awkコマンドにおけるプログラミングの概念
- Format output lines
- Conditional and loops
- Arithmetic and string operations
AWKの構文
$ awk options 'selection _criteria {action }' input-file > output-file

Awkのコマンドの例を示す。
特定の列を印刷する
2番目と3番目の列を印刷するために、以下のコマンドを実行してください。
$ awk '{print $2 "\t" $3}' file.txt

ファイル内のすべての行を印刷する
ファイルのすべての行と列をリストにする場合は、実行してください。
$ awk ' {print $0}' file.txt

特定のパターンに一致するすべての行を印刷する。
特定のパターンに一致する行を印刷したい場合は、構文は以下のようになります。
$ awk '/variable_to_be_matched/ {print $0}' file.txt
例えば、文字「o」を含むすべてのエントリーをマッチさせるには、次のような構文を使用します。
$ awk '/o/ {print $0}' file.txt

$ awk '/e/ {print $0}' file.txt

特定のパターンに一致する列を印刷する。
AWKがパターンに一致する箇所を見つけると、そのコマンドはレコード全体を実行します。特定のフィールドのみを表示する命令を発行することで、デフォルトを変更することができます。例えば、
$ awk '/a/ {print $3 "\t" $4}' file.txt

マッチしたパターンのカウントと印刷
日本語で以下を自然に言い換えるとすると、一つのオプションだけ必要です:
AWKを使用して、パターンに一致する各行の数をカウントして出力することができます。例えば、以下のコマンドは一致するパターンの出現回数を数えます。
$ awk '/a/{++cnt} END {print "Count = ", cnt}' file.txt

文字数が特定の数より多いまたは少ない行を印刷します。
AWKには組み込みのlength関数があり、これは文字列の長さを返します。コマンドの$0変数には行全体が格納され、本体ブロックがない場合、デフォルトのアクションであるprintアクションが実行されます。したがって、テキストファイル内の行が18文字を超える場合、比較結果はtrueとなり、以下のように行が出力されます。
$ awk 'length($0) > 20' file.txt

AWKの出力結果を異なるファイルに保存する。
結果を保存したい場合は、> リダイレクション演算子を使用してください。例えば
$ awk '/a/ {print $3 "\t" $4}' file.txt > Output.txt
以下のようにcatコマンドを使用して結果を検証できます
$ cat output.txt

結論
AWKは、文書のテキストを操作したり特定の機能を実行するために使用できる、もう1つのシンプルなプログラミングスクリプトです。共有されたコマンドは、あなたがまだ知らないか出会っていないもののいくつかです。