Torprendido
Torprendido

Reputation: 55

Back-reference when preprend using sed linux command

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.

Upvotes: 3

Views: 136

Answers (3)

potong
potong

Reputation: 58483

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

Upvotes: 0

RavinderSingh13
RavinderSingh13

Reputation: 133620

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'

Upvotes: 2

anubhava
anubhava

Reputation: 785581

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

Upvotes: 3

Related Questions