Reputation: 27
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
Upvotes: 0
Views: 45
Reputation: 10039
sed 's/\([[:space:];]xId[[:space:]]\{1,\}"\)/\1prefix_/' YourFile
will prefix your string content based on your structure assuming
xld "
in string before your field name Upvotes: 2
Reputation: 158250
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_
.
Upvotes: 1