Use sed to replace part of a string leaving other part represented by regex unchanged

Consider you want to replace part of a sentence and leave other part represented by the regular expression (regex) unchanged. For instance, here's a text file

text1.txt

A Egg
b Egg
C Egg
D Egg
E Pig

You want to change this to

A Chick
b Egg
C Chick
D Chick
E Pig

In this case, Egg in every line with any upper case, space and Egg has changed into Chick. In the regular expression, the target pattern can be represented by [A-Z] Egg.

How can you replace these by ☆ Chick where ☆ is the original upper case character? The command below doesn't/shouldn't work but hope it helps you understand what I want...

sed -i "s/[A-Z] Egg/[A-Z] Chick/g" ./text*.txt # incorrect

1 Answer

Use a capture group that retains the first uppercase letter:

sed "s/\([A-Z]\) Egg/\1 Chick/" file.txt
A Chick
b Egg
C Chick
D Chick
E Pig

Where:

  • \([A-Z]\) is the capture group 1 that contains the first uppercase letter
  • \1 is a backreference to the group 1 (i.e. the content of group 1)

I've remove the -i option to show the result, use it if you want to replace inplace.


If you want to replace inplace in all files text*.txt:

sed -i "s/\([A-Z]\) Egg/\1 Chick/" text*.txt
2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like