Regex Substitution
Regular expressions (regex) are indispensable for text processing in Linux sysadmin workflows. Tools like sed (stream editor) and tr (translate) enable powerful substitution capabilities, from modifying configuration files to sanitizing log data. This section explores how to leverage regex for substitution using these utilities.
sed Substitution: Regex-Powered Text Manipulation¶
sed is the workhorse for regex-based substitution. Its s (substitute) command allows replacing patterns in text, with optional flags for control.
Basic Substitution¶
Replace the first occurrence of a pattern in a line:
Output:Global Substitution¶
Use the g flag to replace all matches in a line:
Case-Insensitive Replacement¶
Add the I flag for case-insensitive matching:
In-Place File Editing¶
Edit files directly with -i:
Advanced: Line Replacement¶
Use c to replace an entire line matching a pattern:
tr Translation: Character-Level Substitution¶
tr (translate) replaces characters in input, but it operates on a character-by-character basis rather than regex. It’s ideal for simple mappings.
Basic Character Translation¶
Replace all a with A and b with B:
Removing Characters¶
Delete all digits from input:
Output:Case Conversion¶
Convert lowercase to uppercase:
Output:Advanced Techniques¶
Combining sed with Pipes¶
Process multiline logs or files in pipelines:
Prefixes lines containing "ERROR" with a warning emoji.Regex Anchors and Ranges¶
Use anchors like ^ (start of line) and $ (end of line) in sed:
Escaping Special Characters¶
Escape regex metacharacters in sed:
Key takeaways¶
sedis essential for regex-based substitution, supporting flags likeg(global) andI(case-insensitive).trexcels at character-level translation but lacks regex capabilities.- Use
sed -ifor in-place file edits, and combinesedwith pipelines for real-time data processing. - Always test substitutions with
echobefore applying them to critical files.