메이커링크

awk를 이용한 로그 파일 데이터 파싱 및 집계: 특정 패턴 추출 및 통계

다양한 형식의 로그 파일에서 특정 정보를 추출하고, 이를 기반으로 통계 데이터를 집계해야 할 때 유용합니다. 특히, 웹 서버 로그, 애플리케이션 로그 등에서 특정 IP의 접속 횟수, 오류 발생 빈도 등을 빠르게 파악할 수 있습니다.

#awk#log parsing#data aggregation#command line#text processing

You are a seasoned MakerLink user, an expert in leveraging command-line tools for efficient data processing. Your task is to generate a practical awk command recipe for parsing and aggregating data from log files, designed to be directly usable within the Cursor IDE. This recipe should be templated to allow for easy adaptation to different log formats and data points.

Objective

To efficiently parse log files using awk to extract specific information and perform aggregations, such as counting occurrences of specific patterns or calculating summary statistics.

Use Case

This recipe is ideal when you need to quickly analyze log data without writing complex scripts or using heavy GUI tools. Common scenarios include:

  • Identifying the most frequent IP addresses accessing a web server.
  • Counting the number of error messages of a particular type.
  • Summarizing request durations or response times.
  • Extracting specific fields from structured or semi-structured log lines.

The awk Recipe Template

This template provides a flexible awk command. You will need to adjust the pattern matching, field extraction, and aggregation logic based on your specific log file structure and analysis goal.

Basic Structure
awk 'BEGIN { ... } /{{Pattern_To_Match}}/ { ... } END { ... }' {{Log_File_Path}}
  • BEGIN { ... }: Initializes variables before processing any lines (e.g., setting counters to 0).
  • /{{Pattern_To_Match}}/ { ... }: This is the core processing block. It executes the commands within the curly braces only for lines that match the specified {{Pattern_To_Match}}. If you want to process all lines, omit the pattern (e.g., { ... }).
  • END { ... }: Executes commands after all lines have been processed (e.g., printing summary results).
  • {{Log_File_Path}}: The path to the log file you want to analyze.
Common awk Field Variables
  • $0: The entire current line.
  • $1: The first field (column) of the current line.
  • $2: The second field, and so on.
  • NF: Number of fields in the current line.
  • FS: Field separator (default is whitespace). You can set this using -F option (e.g., awk -F',' ... for CSV).
Example Scenario: Counting IP Address Occurrences in a Web Server Log

Let's assume a common web server log format (like Apache Combined Log Format) where the IP address is the first field ($1). We want to count how many times each IP address appears.

Log File Example (access.log):

192.168.1.100 - - [10/Oct/2023:13:55:36 +0000] "GET /index.html HTTP/1.1" 200 1024 "-" "Mozilla/5.0 ..."
10.0.0.5 - - [10/Oct/2023:13:56:01 +0000] "POST /submit HTTP/1.1" 201 50 "-" "curl/7.68.0"
192.168.1.100 - - [10/Oct/2023:13:57:15 +0000] "GET /images/logo.png HTTP/1.1" 200 5120 "-" "Mozilla/5.0 ..."
172.16.0.1 - - [10/Oct/2023:13:58:00 +0000] "GET /about HTTP/1.1" 404 200 "-" "Mozilla/5.0 ..."
10.0.0.5 - - [10/Oct/2023:13:59:00 +0000] "GET /status HTTP/1.1" 200 100 "-" "curl/7.68.0"

Goal: Count the occurrences of each IP address.

Template Adaptation:

  • {{Pattern_To_Match}}: We want to process all lines, so we can leave this empty or use . for any line.
  • {{Log_File_Path}}: access.log
  • Logic: Use an associative array in awk where keys are IP addresses ($1) and values are their counts.

The awk Command:

awk '{ count[$1]++ } END { for (ip in count) print ip, count[ip] }' access.log

Explanation:

  • { count[$1]++ }: For each line processed, it takes the first field ($1, which is the IP address) and uses it as a key in the associative array count. The ++ operator increments the value associated with that key. If the key doesn't exist, awk creates it with an initial value of 0 before incrementing.
  • END { for (ip in count) print ip, count[ip] }: After all lines are read, this loop iterates through all the keys (IP addresses) stored in the count array and prints each IP addr
0
스크랩
9
좋아요

메이커링크 에이전트

이 레시피, 직접 따라 하지 말고 맡겨 보세요

휴대폰에서 한 줄로 지시하면 메이커링크 에이전트가 내 PC의 Cursor · Claude Code로 그대로 실행합니다.

무료로 시작하기 원격 PC 1대 무료 · 내 AI 구독 그대로

함께 보면 좋은 레시피

AI 레시피

Cursor AI를 활용한 코드 리팩토링 및 성능 최적화 가이드

Cursor의 AI 코딩 어시스턴트를 사용하여 코드의 가독성을 높이고, 실행 속도를 개선하며, 메모리 사용량을 줄이는 방법을 단계별로 안내합니다. 코드 품질 향상을 위한 실질적인 팁을 제공합니다.

#code refactoring#performance optimization

터미널 레시피

RESTful API 기본 구조 및 인증 토큰 검증 CLI 레시피

RESTful API의 기본 GET, POST 요청을 보내고, Authorization 헤더에 Bearer 토큰을 포함하여 서버 응답을 확인하는 CLI 명령어입니다. API 개발 및 테스트에 유용합니다.

#curl#restful api

AI 레시피

GitOps 기반 Kubernetes 자동 배포 파이프라인 구축 가이드

GitOps 원칙을 사용하여 Kubernetes 환경에 애플리케이션을 자동으로 배포하고 관리하는 방법을 안내합니다. CI/CD와 Git의 장점을 결합한 효율적인 배포 전략을 이해하고 적용하는 데 도움이 됩니다.

#gitops#kubernetes

터미널 레시피

Helm으로 Kubernetes 애플리케이션 패키징 및 기본 배포

Helm 차트를 생성하고 로컬 Kubernetes 클러스터에 간단한 애플리케이션을 배포하는 과정을 보여주는 명령어 레시피입니다. CI/CD 파이프라인 연동의 기초로 활용할 수 있습니다.

#helm#kubernetes

AI 레시피

SQL vs NoSQL 데이터베이스 비교 및 선택 가이드

SQL과 NoSQL 데이터베이스의 핵심적인 차이점을 이해하고, 프로젝트 요구사항에 맞는 데이터베이스를 선택하는 데 도움을 주는 가이드입니다.

#sql#nosql

AI 레시피

GitOps 핵심 개념과 CI/CD 파이프라인 구축 전략 가이드

GitOps의 기본 원리를 이해하고, Docker, Kubernetes, GitHub Actions를 활용하여 자동화된 CI/CD 파이프라인을 구축하는 방법을 안내합니다. 실무 적용에 필요한 핵심 개념과 전략을 다룹니다.

#gitops#cicd