sed

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

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