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?

awkワンライナー集

Last updated at Posted at 2025-10-23

CLIで実行するときの基本的な使い方

awk 'パターン { アクション }' ファイル
  • パターンは各行ごとに評価され、真の場合にアクションが実行される(パターンを省略すると、全行がアクションの対象となる)
  • アクション は {} 内で記述(省略するとそのまま出力される)
  • $1,$2、... → 行のフィールド(列)
  • $0 → 行全体

1. 特定の列を抜き出す

awk '{print $1}' file.txt

2. 区切り文字を指定する

awk -F, '{print $2}' file.csv

3. 条件に一致する行を抽出

awk '$3>100' file.txt

4. 行数を数える(最終行の行番号を表示する)

awk 'END {print NR}' file.txt

5. 数値の合計を計算

awk '{sum += $2} END {print sum}` file.txt

2列目の合計値を出力する

6. 平均値を計算

awk '{sum += $3; count++} END {print sum/count}' file.txt

7. ヘッダーを除いて処理

awk 'NR > 1 {sum += $2} END {print sum}' file.txt

1行目(ヘッダ)を飛ばして2列目の合計を取る

8. 列を入れ替えて表示

awk '{print $2, $1}' file.txt

9. パターンマッチング

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

ERRORを含む行だけ抽出
(このコマンドならgrepでも可能)

10. 行番号を付与

awk `{print NR, $0}` file.txt

全行の先頭に行番号をつけて出力

少し高度な例

重複行を数える(sortを使わない)

awk `{count[$0]++} END {for (line in count) print count[line], line}` file.txt

count[$0]は各行の文字列自体をキーとした連想配列
for (line in count) では、count配列のキーをすべて取り出している

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?