Search code examples
regexperlsed

Perl or sed: Regex replace with group capture


I cannot seem to make sed do a regex replace with group capture in this example:

  • Input: "DONE project 1"
  • Desired putput: "project 1 DONE"

What I tried with sed:

$ echo "DONE project 1" | sed -E 's/^DONE(.*)$/$1 DONE/g'
$1 DONE  # fail! no group capture in `sed`?

Is there a way to do this in Perl?

Actually this is part of an AppleScript used by DEVONthink[^1], and I realized that sed was not able to do regex search/replace with group capture.

[^1]: DEVONthink's search/replace script with AppleScript usage

set transformedName to do shell script "echo " & quoted form of itemName & " | sed -E 's/" & sourcePattern & "/" & destPattern & "/g'"
set name of selectedItem to transformedName

Solution

  • sed can easily do this, use \1, $1 is the Perl backreference syntax:

    sed -E 's/^DONE(.*)/\1 DONE/g'
    

    .* matches all the line up to the end, so you do not have to use $ in the LHS.