Use sed to edit a value within quotes

69 views Asked by At

xI have a text in this form:

foo1   bar1   xId "myId1";yId "something"
foo2   bar2   xId "myId2";yId "something"
foo2   bar2   yId "something";xId "myId3"

How can I use sed to edit the myId field? I want to append a value before it, like this:

foo1   bar1   xId "prefix_myId1";yId "something";
foo2   bar2   xId "prefix_myId2";yId "something";
foo2   bar2   yId "something";xId "prefix_myId2";

I cannot use awk because xId is not always in the same place in my file. However, it is guaranteed that the line is in this format: someStuff xId "myContent"; someOtherStuff

Thanks a lot, I can use

sed 's/\(.*xId \)[^ ]*\(;.*\)/ a \1"newValue"\2/'

but it replaces the contents by newValue instead of prefixing it...

The capture group should make use of xId

EDITED TO SHOW TRICKY PART, THANKS FOR YOUR COMMENTS

2

There are 2 answers

4
hek2mgl On BEST ANSWER

With sed:

 sed -r 's/(xId\s*[^"]*")([^"]*)/\1prefix_\2/' input.txt

I'm using two capturing groups: ([^"]*") catches everything after the xId before the next opening " including them. ([^"]*) selects the content between the ".

In the replacement pattern I reassemble the groups and inject the term prefix_.

2
NeronLeVelu On
sed 's/\([[:space:];]xId[[:space:]]\{1,\}"\)/\1prefix_/' YourFile

will prefix your string content based on your structure assuming

  • xld is not the first field without space before
  • there is no xld " in string before your field name