lacosteaef
lacosteaef

Reputation: 55

Using sed to append string with value within string

I have strings that end with:

...", "VERI-1000")

and I am trying to use sed (or any other tool) to have them formatted like

...", "(VERI-1000)" uid="1000"/>

The "VERI" and the "1000" values change multiple times so it's not always "VERI" and not always "1000"

I suppose then I am trying to search for the numerical value that precedes the ") string and then insert that value after uid="

Upvotes: 2

Views: 70

Answers (2)

Lev Levitsky
Lev Levitsky

Reputation: 65841

With GNU sed you can do something like this:

sed -r 's_([[:digit:]]+)"\)$_& uid="\1"/>_'

The command replaces this:

([[:digit:]]+)"\)$
^ start numbered group (number 1)
 ^^^^^^^^^^^^ any number of digits
             ^ close numbered group
              ^^^^ quote, bracket, EOL

with this:

& uid="\1"/>
^ all of the matched string
       ^^ contents of group number 1

Example:

sed -r 's_([[:digit:]]+)"\)$_& uid="\1"/>_' <<<'...", "VERI-1000")'
...", "VERI-1000") uid="1000"/>

POSIX-compatible way:

sed 's_\([[:digit:]]\{1,\}\)")$_& uid="\1"/>_'

Upvotes: 0

anubhava
anubhava

Reputation: 785876

Try this sed:

sed -i.bak 's~"\([^"-]*\)-\([0-9]*\)")~"(\1-\2") uid="\2"/>~' file

Upvotes: 2

Related Questions