惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - 司徒正美
T
The Blog of Author Tim Ferriss
雷峰网
雷峰网
S
Secure Thoughts
GbyAI
GbyAI
Google DeepMind News
Google DeepMind News
P
Proofpoint News Feed
G
GRAHAM CLULEY
MongoDB | Blog
MongoDB | Blog
WordPress大学
WordPress大学
M
MIT News - Artificial intelligence
Martin Fowler
Martin Fowler
C
Cyber Attacks, Cyber Crime and Cyber Security
I
Intezer
A
About on SuperTechFans
Hugging Face - Blog
Hugging Face - Blog
T
Threatpost
S
Securelist
T
Tenable Blog
博客园_首页
P
Privacy International News Feed
Cisco Talos Blog
Cisco Talos Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
月光博客
月光博客
C
CXSECURITY Database RSS Feed - CXSecurity.com
小众软件
小众软件
美团技术团队
Project Zero
Project Zero
The Cloudflare Blog
L
Lohrmann on Cybersecurity
The Register - Security
The Register - Security
B
Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
L
LINUX DO - 热门话题
C
CERT Recently Published Vulnerability Notes
C
Cybersecurity and Infrastructure Security Agency CISA
有赞技术团队
有赞技术团队
IT之家
IT之家
A
Arctic Wolf
Scott Helme
Scott Helme
Latest news
Latest news
T
Tailwind CSS Blog
Jina AI
Jina AI
Microsoft Azure Blog
Microsoft Azure Blog
Recent Announcements
Recent Announcements
Cyberwarzone
Cyberwarzone
宝玉的分享
宝玉的分享
The Hacker News
The Hacker News
S
Schneier on Security
Y
Y Combinator Blog

Stonecharioteer on Tech

I Traced My Traffic Through a Home Tailscale Exit Node What Was I Reading Last? In Three Not-So-Easy Pieces Dogfooding Is Hard Code blocks in your books, finally GoForGo v0.9.0 Merrilin - We built an app to read books I use a Macbook now Data Structures & Algorithms - Preparing for Interviews Using a local DNS namespace for local service discovery Direction KOllector - Publishing KOReader Highlights gbt: branches touched in the last 24 hours A Soiree into Symbols in Ruby Some Smalltalk about Ruby Loops Ruby Blocks Returning from Ruby Blocks, Procs and Lambdas My Linux Laptop Finally Works: How Claude Helped Me Fix Years of Annoyances TIL: Watchexec - Modern File Watching for Development Workflows A Less Busy Mind GoForGo - Learn Go through live examples Migrating My Old Blog to Hugo with Claude The Qtile Window Manager: A Python-Powered Tiling Experience Read the RFCs that Built the Internet Py-x-Protobuf - Or How I Learned to Stop Worrying and Love Protocol Buffers Python Reverse a List New Beginnings Leaving ChainSafe Systems Screen Lock for Cinnamon Desktop using Zenity and Terminal Commands Crews Not Teams A System for Getting Better at LeetCode So Far So Rust Retrying HTTP Requests with Rust A Primer on Control Charts Learning Rust Explicit is Better than Implicit: Rust for Pythonistas Using Custom Delimiters in Jinja Templates TIL: Creating Fixed Length Iterables in Python Documentation Without Assumption Vagrant Python - A Reflection in 2022 Learning Golang No, A Virtual Machine Is Not Enough: Why Developers Need Native Linux Empathy in Tech For Those Who Came in Late A Weekend With PostgreSQL TIL: Gooey and Python Fire for Quick GUIs and CLIs TIL: 2ality - Dr. Axel Rauschmayer's JavaScript Blog TIL: MassDNS - High-Performance Bulk DNS Lookups TIL: Matomo Analytics, Google Tech Writing, Memory Programming, and NES TV Signals TIL: MontyDB - MongoDB Implemented in Python Returning to the Craft of Programming TIL: CPUFetch, OneFetch, and Learn CSS TIL: DNS Performance Testing and Pi-hole with Unbound TIL: Eli Bendersky's Blog, Awesome By Example, NoCoDB, and Martin Kleppmann TIL: CRDTs, Extreme HTTP Performance, and BYTEPATH Game TIL: AutoInvent, ASGI, Python Packaging, RAPIDS GPU Computing, and FlaskCon TIL: MangaDesk - Terminal Client for MangaDex TIL: McFly - Smart Shell History Search TIL: Siege Load Testing and Awesome FastAPI Resources TIL: Ventoy Bootable USB and Justniffer Network Analysis TIL: CLI Code Review, Git Split Diffs, and Internal Combustion Engine TIL: Benford's Law, Web Security Headers, Event Sourcing, and Mozilla Security Guidelines How to Write Documentation - The README.md File The Importance of Documentation TIL: NNgroup UX Research, SponsorBlock, and Labella Python Library TIL: The Little Book of Rust Macros and Rust Performance Book TIL: Git-Bug Distributed Issue Tracker and Omni Kubernetes Monitoring TIL: Zellij - Modern Terminal Multiplexer TIL: How Discord Handles 2.5 Million Concurrent Voice Users TIL: Volumio - The Audiophile Music Player TIL: Areopagitica - Milton's Defense of Free Speech TIL: Fast Node Manager, Zoxide Smart CD, Technical Writing, PyO3, and Qubes OS TIL: Slurm Workload Manager for HPC Clusters TIL: Data Visualization Guide and Oso Authorization Academy TIL: CORS Deep Dive, Piku Tiny PaaS, Rust Strings, and Deno Standard Library TIL: Raspberry Pi OS Development, Vim Beginner Guide, Password Management, and QueryBook TIL: uBlock Origin Performance Optimization on Firefox TIL: Breaking PostgreSQL at Scale and LeetCode Problem Patterns TIL: Awesome Tmux Resources for Terminal Multiplexing TIL: Grit - A Multitree-Based Personal Task Manager TIL: Lens 4.2 Kubernetes IDE, Shell Scripting Guide, and Dark HTTP Server Do The Job You Hate So You Won't Hate The Job You Love TIL: Innernet VPN Solution and NoteCalc Calculator App TIL: Argo CD for GitOps and Lens Kubernetes IDE TIL: Modern Rust CLI Tools - System Monitoring, HTTP Requests, and DNS TIL: tz - A Time Zone Helper Tool TIL: Distributed Systems Education, Fallacies, and Self-Hosted Internet Archiving TIL: Real-Time Voice Cloning Technology TIL: ChartMuseum for Helm, AMD's Corporate Journey, and Kubernetes Pod Scaling TIL: Docker and Kubernetes Tools - Whaler, Descheduler, and Dive TIL: Post-Mortem Collection, Terminal Plotting, and Technical Twitter TIL: Dark Mode Toggle Web Component by Google Chrome Labs TIL: Python eval(), exec(), and compile() Functions TIL: Camelot PDF Tables, PostgreSQL Row Level Security, Zerodha Varsity, and Write Yourself a Git TIL: fuser Command for Process and File Investigation TIL: i Hate Regex - The Ultimate Regex Cheat Sheet TIL: Dolt - Git for Data and Database Version Control TIL: x86 Assembly Programming and SafeEyes Break Reminder TIL: Comprehensive Distributed Systems Reading List TIL: Cosmopolitan C Library, Distributed Systems Book, High Performance Browser Networking, and Rust Roguelike Tutorial
TIL: tr Command for Stream Translation and Character Manipulation
2020-11-01 · via Stonecharioteer on Tech

Today I discovered the versatile tr command for translating and manipulating character streams in Unix pipelines.

Basic tr Command Usage

The tr (translate) command transforms characters from stdin according to specified rules:

Character Translation:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
# Convert lowercase to uppercase
echo "hello world" | tr 'a-z' 'A-Z'
# Output: HELLO WORLD

# Convert uppercase to lowercase
echo "HELLO WORLD" | tr 'A-Z' 'a-z'
# Output: hello world

# Replace specific characters
echo "hello-world" | tr '-' '_'
# Output: hello_world

# Multiple character replacement
echo "hello world" | tr 'hw' 'HW'
# Output: Hello World

Character Deletion:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# Delete specific characters
echo "hello123world456" | tr -d '0-9'
# Output: helloworld

# Delete whitespace
echo "hello   world" | tr -d ' '
# Output: helloworld

# Delete newlines (join lines)
cat multiline.txt | tr -d '\n'

Character Sets and Ranges:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
# Using predefined character classes
echo "Hello World 123!" | tr '[:upper:]' '[:lower:]'
# Output: hello world 123!

echo "Hello World 123!" | tr -d '[:punct:]'
# Output: Hello World 123

echo "Hello World 123!" | tr -d '[:digit:]'
# Output: Hello World !

# Available character classes:
# [:alnum:]  - alphanumeric characters
# [:alpha:]  - alphabetic characters
# [:digit:]  - numeric characters
# [:lower:]  - lowercase letters
# [:upper:]  - uppercase letters
# [:punct:]  - punctuation characters
# [:space:]  - whitespace characters

Advanced tr Operations

Squeeze Repeated Characters:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# Squeeze multiple spaces into single space
echo "hello    world" | tr -s ' '
# Output: hello world

# Squeeze any whitespace
echo -e "hello\t\t\nworld" | tr -s '[:space:]'
# Output: hello world

# Remove duplicate characters
echo "hellooo wooorld" | tr -s 'o'
# Output: helo world

Complement Operations:

1
2
3
4
5
6
7
# Keep only specified characters (delete complement)
echo "abc123def456" | tr -cd '[:digit:]'
# Output: 123456

# Delete everything except letters and spaces
echo "Hello, World! 123" | tr -cd '[:alpha:][:space:]'
# Output: Hello World

Practical Use Cases

Data Cleaning:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
# Clean CSV data - replace commas with tabs
cat data.csv | tr ',' '\t'

# Remove Windows line endings
cat windows_file.txt | tr -d '\r'

# Convert DOS to Unix line endings
tr -d '\r' < dos_file.txt > unix_file.txt

# Clean phone numbers
echo "(555) 123-4567" | tr -cd '[:digit:]'
# Output: 5551234567

Text Processing:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# ROT13 cipher
echo "hello" | tr 'a-zA-Z' 'n-za-mN-ZA-M'
# Output: uryyb

# Create URL-safe strings
echo "Hello World!" | tr '[:upper:][:space:][:punct:]' '[:lower:]--'
# Output: hello-world-

# Extract words (replace non-letters with newlines)
echo "hello,world;testing" | tr -cs '[:alpha:]' '\n'
# Output:
# hello
# world
# testing

Log Analysis:

1
2
3
4
5
6
7
8
# Count unique IP addresses in log
cat access.log | tr -s ' ' | cut -d' ' -f1 | sort | uniq -c

# Extract only numeric data from mixed content
cat mixed_data.txt | tr -cd '[:digit:]\n'

# Convert log timestamps
cat log.txt | tr ':' '-'  # Replace colons with dashes

System Administration:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# Generate random passwords (simple method)
tr -cd '[:alnum:]' < /dev/urandom | head -c 16
# Output: aB3xK9mP2qR8vN4L

# Convert file paths
echo "/path/to/file" | tr '/' '\\'
# Output: \path\to\file

# Clean environment variables
echo "$PATH" | tr ':' '\n'  # Show PATH entries one per line

Advanced Patterns

Character Mapping Tables:

1
2
3
4
5
6
7
8
9
# Create substitution cipher
plaintext="abcdefghijklmnopqrstuvwxyz"
ciphertext="zyxwvutsrqponmlkjihgfedcba"
echo "secret message" | tr "$plaintext" "$ciphertext"
# Output: hvxivg nvhhztv

# Leetspeak conversion
echo "elite hacker" | tr 'eElLoOaAsS' '33110044$$'
# Output: 3lit3 h4ck3r

Combining with Other Commands:

1
2
3
4
5
6
7
8
# Word frequency analysis
cat text.txt | tr -cs '[:alpha:]' '\n' | tr '[:upper:]' '[:lower:]' | sort | uniq -c | sort -nr

# Extract email domains
grep -o '[a-zA-Z0-9._%+-]*@[a-zA-Z0-9.-]*\.[a-zA-Z]*' emails.txt | tr '[:upper:]' '[:lower:]' | cut -d'@' -f2 | sort | uniq

# Convert camelCase to snake_case
echo "camelCaseVariable" | tr '[:upper:]' '[:lower:]' | sed 's/\([a-z]\)\([A-Z]\)/\1_\2/g'

Performance Considerations:

1
2
3
4
5
# tr is very fast for simple transformations
time cat large_file.txt | tr '[:lower:]' '[:upper:]' > /dev/null

# For complex patterns, tr + other tools often faster than sed/awk
time cat large_file.txt | tr -d '[:punct:]' | tr -s '[:space:]' > /dev/null

The tr command is particularly valuable because it’s designed for character-level transformations and is extremely fast, making it ideal for preprocessing data in complex pipelines before more sophisticated tools like sed, awk, or grep operate on it.