Back-reference when preprend using sed linux command

100 Views Asked by At

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.

3

There are 3 best solutions below

0
anubhava On BEST ANSWER

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
2
RavinderSingh13 On

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'
0
potong On

This might work for you (GNU sed):

sed -E '/monkey/i m' file

Insert the line containing m only above a line containing monkey.

Perhaps a more generic solution would be to insert the first character of a word above that word:

sed -E 'h;s/\B.*//;G' file

Make copy of the word.

Remove all but the first character of the word.

Append the original word delimited by a newline.

Print the result.

N.B. \B starts a match between characters of a word. \b represents the start or end of a word (as does \< and \> separately).