# Text Processing Guide
Comprehensive guide to text and log processing with hawk.
## 📖 Table of Contents
- [Text Processing Fundamentals](#text-processing-fundamentals)
- [Log File Analysis](#log-file-analysis)
- [String Operations](#string-operations)
- [Pattern Matching and Filtering](#pattern-matching-and-filtering)
- [Text Transformation](#text-transformation)
- [Data Extraction](#data-extraction)
- [Advanced Text Patterns](#advanced-text-patterns)
- [Performance Optimization](#performance-optimization)
- [Real-world Examples](#real-world-examples)
## Text Processing Fundamentals
### Understanding Text Mode
hawk processes text files line-by-line when using the `--text` flag, treating each line as a string element in an array.
```bash
# Force text processing mode
hawk --text 'query' file.txt
hawk -t 'query' file.txt
# When to use --text flag
### Text vs Structured Data
| **Auto-detect** | JSON, YAML, CSV files | `hawk '.field' data.json` |
| **Text mode (-t)** | Log files, plain text | `hawk -t '. \| contains("ERROR")' app.log` |
| **Force text** | Ambiguous files | `hawk -t 'query' structured.log` |
### Basic Text Processing Workflow
```bash
3. Transform text → hawk -t '. | map(operation)' file.txt
4. Extract data → hawk -t '. | map(. | split(" ")[0])' file.txt
5. Analyze results → hawk -t '. | unique | count' file.txt
```
## Log File Analysis
### Common Log Formats
#### Application Logs
```
2024-01-15 09:00:01 INFO Application started successfully
2024-01-15 09:00:02 DEBUG Loading configuration from /etc/app/config.json
2024-01-15 09:01:23 ERROR Failed to process user request: connection timeout
2024-01-15 09:01:24 INFO Retrying connection...
2024-01-15 09:02:45 WARN High memory usage detected: 85%
```
**Analysis Examples:**
```bash
# Find all error messages
# Extract timestamps
# Count log levels
# Get unique dates
#### Docker Container Logs
```
2024-01-15T10:30:45Z web_server GET /api/users 200 0.045s
2024-01-15T10:30:46Z database_service Connected to MySQL
2024-01-15T10:30:47Z web_server POST /api/auth 401 0.012s
2024-01-15T10:30:48Z cache_service Redis cache miss for key:user:123
```
**Analysis Examples:**
```bash
# Extract service names
# HTTP status code analysis
# Service activity timeline
#### Nginx/Apache Access Logs
```
192.168.1.100 - - [15/Jan/2024:10:30:45 +0000] "GET /api/users HTTP/1.1" 200 1234 "https://example.com" "Mozilla/5.0"
192.168.1.101 - - [15/Jan/2024:10:30:46 +0000] "POST /api/auth HTTP/1.1" 401 567 "-" "curl/7.68.0"
192.168.1.102 - - [15/Jan/2024:10:30:47 +0000] "GET /favicon.ico HTTP/1.1" 404 0 "https://example.com" "Mozilla/5.0"
```
**Analysis Examples:**
```bash
# Extract IP addresses
# Status code distribution
# Find 4xx and 5xx errors
# Top user agents
# Requests per hour
#### System Logs (syslog format)
```
Jan 15 10:30:45 server01 kernel: [12345.678] TCP: Peer 192.168.1.100:443 unexpectedly shrunk window
Jan 15 10:30:46 server01 sshd[1234]: Accepted password for user from 192.168.1.200 port 22 ssh2
Jan 15 10:30:47 server01 systemd[1]: Started User Manager for UID 1000.
```
**Analysis Examples:**
```bash
# Extract service names
# SSH connection analysis
# System service events
# Error pattern analysis
## String Operations
### Basic String Transformations
```bash
# Case conversion
# Whitespace management
hawk -t '. | map(. | trim_end)' text.txt # Remove trailing spaces only
# String analysis
```
### Advanced String Operations
```bash
# Text replacement
# Substring extraction
# String splitting with array access (NEW!)
hawk -t '. | map(. | split(":")[1] | trim)' key_value.txt # Extract values
```
### Multiple Field String Operations (NEW!)
```bash
# Apply same operation to multiple fields in structured data
hawk '.logs[] | map(.message, .details | lower)' structured_logs.json
```
## Pattern Matching and Filtering
### Basic Pattern Matching
```bash
# Contains pattern
# Case-insensitive search
# Multiple patterns (OR logic)
# Exclude patterns
### Advanced Pattern Matching
```bash
# String starts/ends with pattern
# Length-based filtering
# Complex conditions
```
### Log Level Filtering
```bash
# Standard log levels
hawk -t '. | select(. | contains("WARN"))' app.log
hawk -t '. | select(. | contains("ERROR"))' app.log
hawk -t '. | select(. | contains("FATAL"))' app.log
# Severity filtering (ERROR and above)
# Time-based filtering
```
## Text Transformation
### Data Extraction
```bash
# Extract timestamps from logs
# Extract IP addresses from access logs
# Extract HTTP methods
# Extract file paths
# Extract domains from URLs
### CSV-like Text Processing
```bash
# Process comma-separated values
# Process tab-separated values
# Process pipe-separated values
# Join processed data back
### Key-Value Extraction
```bash
# Extract values from key=value format
# Extract specific keys
# Process JSON-like logs
## Data Extraction
### Email and URL Extraction
```bash
# Extract email addresses (basic pattern)
# Extract domains from emails
# Extract URLs (basic pattern)
### Numeric Data Extraction
```bash
# Extract numbers from text
# Extract percentages
# Extract timestamps (ISO format)
# Extract version numbers
### Error Code and Status Extraction
```bash
# HTTP status codes
# Exit codes from logs
# Error numbers
## Advanced Text Patterns
### Multi-line Log Processing
```bash
# Process stack traces (keep related lines together)
# Group by session ID
# Process multiline JSON logs (single line JSON per log entry)
### Performance Log Analysis
```bash
# Response time analysis
# Memory usage tracking
# CPU usage extraction
### Security Log Analysis
```bash
# Failed login attempts
# Suspicious activity patterns
# IP-based analysis
## Performance Optimization
### Efficient Text Processing
```bash
# ✅ Filter early in pipeline
# ❌ Process everything then filter
# ✅ Use specific operations
# ❌ Use complex operations when simple ones suffice
### Memory Management
```bash
# ✅ Process in chunks for large files
# ✅ Sample large datasets
### Slicing for Performance (NEW!)
```bash
# ✅ Process recent logs only
# ✅ Sample from different time periods
# ✅ Top/bottom analysis
```
## Real-world Examples
### Complete Log Analysis Workflows
#### Web Server Log Analysis
```bash
# 1. Overview of traffic
# 2. Error analysis
# 3. Top pages
# 4. Traffic patterns by hour
# 5. User agent analysis
#### Application Error Investigation
```bash
# 1. Error trend analysis
# 2. Error types
# 3. Related warnings
#### System Performance Monitoring
```bash
# 1. Memory usage trends
# 2. Disk space monitoring
# 3. Network activity
# 4. Process analysis
#### Security Log Analysis
```bash
# 1. Authentication failures
# 2. Unusual access patterns
# 3. Brute force detection
# 4. Geographic analysis (if GeoIP data available)
#### DevOps Pipeline Logs
```bash
# 1. Build success/failure rates
# 2. Deployment timing
# 3. Test results analysis
# 4. Resource usage during builds
## Best Practices
### Text Processing Guidelines
1. **Always use --text flag for log files**: Prevents YAML/JSON misdetection
2. **Filter early**: Apply `select()` before expensive operations
3. **Use specific extractors**: Prefer `split()[index]` over complex regex alternatives
4. **Handle edge cases**: Check for empty results and missing fields
5. **Sample large files**: Use slicing for performance with huge datasets
### Common Patterns
```bash
# ✅ Good: Extract then analyze
# ✅ Good: Filter then transform
# ✅ Good: Use appropriate data types
# ✅ Good: Handle missing data
### Debugging Text Processing
```bash
# Check data structure
# Validate operations step by step
# Check for empty or problematic lines
```
---
**Related Documentation:**
- [Getting Started](getting-started.md) - Basic hawk introduction
- [String Operations](string-operations.md) - Detailed string processing reference
- [Query Language](query-language.md) - Complete syntax guide
- [Log Analysis Examples](examples/log-analysis.md) - Real-world log processing cases