Issue
i want to replace a unknown string between two strings.
(1(...) 2(...) 3(...))
I use:
sed -i "s/2(.*)/2(new)/g"
but i'm getting. (It take the last ')')
(1(hello) 2(new)
And i want :
(1(...) 2(new) 3(...))
Someone can help me please ?
Edit :
Thank to the answerers, i have another case:
"data_1": [...], "data_2": [...], "data_3": [...]
I want to insert a string between ' "data_2": [ ' and the first occurence of ']' after data_2
Solution
sed
uses greedy matching so OP's attempt - 2(.*)
- is going to match the 1st literal 2(
plus the longest string that ends with )
; consider the following where our match starts with the first 2(
and runs to the last )
:
$ echo '(1(...) 2(...) 3(...) 2(abc) 4(...)) more stuff' | sed 's/2(.*)/2(new)/'
(1(...) 2(new) more stuff
To limit the match to the first matching )
there are a few approaches, one idea is to be explicit about what does and does not match, consider:
$ echo '(1(...) 2(...) 3(...) 2(abc) 4(...)) more stuff' | sed 's/2([^)]*)/2(new)/'
(1(...) 2(new) 3(...) 2(abc) 4(...)) more stuff
In this the case we use 2([^)]*)
which says to match on 2(
followed by any number of characters that are not a )
([^)]*
) followed by a )
.
To match on all non-greedy occurrences of 2(...)
(where the ...
means any non-)
character) we can add the g
lobal qualifier on the end of the sed
script, eg:
$ echo '(1(...) 2(...) 3(...) 2(abc) 4(...)) more stuff' | sed 's/2([^)]*)/2(new)/g'
(1(...) 2(new) 3(...) 2(new) 4(...)) more stuff
Answered By - markp-fuso Answer Checked By - Katrina (WPSolving Volunteer)