Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sed to find and replace a substring, then insert the full string

Example:
file contains the following:

lebnassvm0a-dr      test1      /vol/test1
lebnassvm0a-dr      test2      /test2
lebnassvm0a-dr      test3      /test3
stgtestsvm1-dr      test21      /test21
stgtestsvm1-dr      test22      /test22
stgtestsvm1-dr      test23      /test23

I want to find the "-dr" and replace with "-drt" and insert the full string in front of the existing, like this:

lebnassvm0a-drt lebnassvm0a-dr      test1      /vol/test1
lebnassvm0a-drt lebnassvm0a-dr      test2      /test2
lebnassvm0a-drt lebnassvm0a-dr      test3      /test3
stgtestsvm1-drt stgtestsvm1-dr      test21      /test21
stgtestsvm1-drt stgtestsvm1-dr      test22      /test22
stgtestsvm1-drt stgtestsvm1-dr      test23      /test23

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

What I would do:

$ sed -E 's/^([^-]+-dr)/\1t \1/' file
lebnassvm0a-drt lebnassvm0a-dr      test1      /vol/test1
lebnassvm0a-drt lebnassvm0a-dr      test2      /test2
lebnassvm0a-drt lebnassvm0a-dr      test3      /test3
stgtestsvm1-drt stgtestsvm1-dr      test21      /test21
stgtestsvm1-drt stgtestsvm1-dr      test22      /test22
stgtestsvm1-drt stgtestsvm1-dr      test23      /test23

The regular expression matches as follows:

Node Explanation
^ the beginning of the string anchor
( group and capture to \1:
[^-]+ any character except: - (1 or more times (matching the most amount possible))
-dr ‘-dr’
) end of \1
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading