Console9

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

  1. Capture a group with \( and \) and reference it with \1 in the replacement. sed extracts the version number from a string:

    echo "version: 3.2.1" | sed 's/version: \(.*\)/\1/'

    Output: 3.2.1

  2. Use extended regex ( -E or -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/2026

  3. Swap two words using two capture groups:

    echo "first last" | sed -E 's/(\w+) (\w+)/\2 \1/'

    Output: last first