3

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
    Backreferences only exist [within a regular expression](https://www.gnu.org/software/sed/manual/html_node/Back_002dreferences-and-Subexpressions.html#index-back_002dreference) or [in the replacement part of the `s///` command](https://www.gnu.org/software/sed/manual/html_node/The-_0022s_0022-Command.html#index-Backreferences_002c-in-regular-expressions) – glenn jackman Oct 11 '22 at 14:09

3 Answers3

3

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
anubhava
  • 761,203
  • 64
  • 569
  • 643
2

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'
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
0

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).

potong
  • 55,640
  • 6
  • 51
  • 83