Home > Net >  Back-reference when preprend using sed linux command and i sed command
Back-reference when preprend using sed linux command and i sed command

Time:10-12

I'm trying to prepend the first character of "monkey" using this command:

echo monkey | sed -E '/(.)onkey/i \1'

But when I use it like this, the output shows

1
monkey

I actually hope to see:

m
monkey

But back-reference doesn't work. Please someone tell me if it is possible to use Back-reference with \1. Thanks in advance.

CodePudding user response:

You may use this sed:

echo 'monkey' | sed -E 's/(.)onkey/\1\n&/'

m
monkey

Here:

  • \1: is back-reference for group #1
  • \n: inserts a line break
  • &: is back-reference for full match

CodePudding user response:

With any version of awk you can try following solution, written and tested with shown samples. Simply searching regex ^.onkey and then using sub function to substitute starting letter with itself new line and itself and printing the value(s).

echo monkey | awk '/^.onkey/{sub(/^./,"&\n&")} 1'
  • Related