How to use sed with regex groups and back-references
Capture text with regex groups and reuse it in replacements using sed back-references.
How to use sed with regex groups and back-references
Capture text with regex groups and reuse it in replacements using sed back-references.
Prerequisites
- sed installed (GNU or BSD).
Step-by-Step: Use Regex Groups in sed
Capture a group with
\(and\)and reference it with\1in the replacement. sed extracts the version number from a string:echo "version: 3.2.1" | sed 's/version: \(.*\)/\1/'Output:
3.2.1Use extended regex (
-Eor-r) for cleaner group syntax without backslash escaping:echo "2026-03-30" | sed -E 's/([0-9]{4})-([0-9]{2})-([0-9]{2})/\3\/\2\/\1/'Output:
30/03/2026Swap two words using two capture groups:
echo "first last" | sed -E 's/(\w+) (\w+)/\2 \1/'Output:
last first