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?

ログからURLの一部だけ抽出してリアルタイムに出力(重複除去&ソート)

Posted at

以下のようなパイプラインで実現できます。

1. ファイルの最後 100 行を対象にする場合

tail -n 100 /path/to/your.log \
  | grep '/api/v1/' \
  | awk -F'/api/v1/' '{ split($2, a, "/"); print "api/v1/" a[1] }' \
  | sort -u

2. リアルタイムに追いかけながら重複除去・ソートする場合

tail -f /path/to/your.log \
  | grep --line-buffered '/api/v1/' \
  | awk -F'/api/v1/' '{ split($2, a, "/"); print "api/v1/" a[1] }' \
  | sort -u

各コマンドの解説

  1. tail -n 100tail -f

    • ログの最後数行を取る、またはリアルタイムに追加行をストリーミング
  2. grep '/api/v1/'

    • /api/v1/ を含む行だけを抽出
  3. awk -F'/api/v1/' '{ split($2, a, "/"); print "api/v1/" a[1] }'

    • -F'/api/v1/' で行を2つに分割
    • $2 の先頭から最初の / まで(ここでは 90_x)を取り出し、api/v1/ を付与
  4. sort -u

    • ソートしたうえで重複行を削除

これで、ログ中に出現したすべての api/v1/90_x 部分だけをユニークに拾ってソートできます。

PowerShell または Git Bash(もしくは WSL)を使えば、Linuxに近い操作が可能


✅ 方法1:PowerShell でやる(純正Windows環境)

PowerShell は Linux のようなワンライナー処理には向きませんが、以下のようにすれば似たことができます:

Get-Content .\your.log -Tail 100 |
  Select-String '/api/v1/' |
  ForEach-Object {
    if ($_ -match '/api/v1/([^/]+)') {
      "api/v1/$($matches[1])"
    }
  } | Sort-Object -Unique

✅ 解説:

  • Get-Content -Tail 100 → 最後の100行を取得
  • Select-String/api/v1/ を含む行を抽出
  • -match → 正規表現で api/v1/ の次の1セグメント(例:90_x)を抽出
  • Sort-Object -Unique → 重複排除+ソート

✅ 方法2:Git Bash(おすすめ)

Git for Windows をインストールすると、Linux のような Bash が使えるようになります。

Git Bash を開いて、以下の Linux コマンドと同様のワンライナーがそのまま使えます:

tail -n 100 your.log \
  | grep '/api/v1/' \
  | awk -F'/api/v1/' '{ split($2, a, "/"); print "api/v1/" a[1] }' \
  | sort -u

✅ 方法3:WSL(Windows Subsystem for Linux)

WSL(Ubuntu など)を有効にすれば、本物の Linux シェルが使えます。

wsl
cd /mnt/c/Users/YourName/Downloads
tail -n 100 your.log | grep '/api/v1/' | awk ... | sort -u

Windowsでやる場合のまとめ

方法 特徴 難易度
PowerShell Windows標準。やや冗長な構文。 ★★☆
Git Bash Linuxコマンドがそのまま使える。 ★☆☆(おすすめ)
WSL 完全なLinux環境。拡張性が高い。 ★★★

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?