command line - Change string within Brackets with non_greedy pattern - Ask Ubuntu


i trying change string within (), , following non-greedy pattern.

input:

this 1(the house owner 2(pet-name john james) john , friend 3(unknown name james) james fred) 

output:

this 1(the house owner 2(pet-name xxx-john xxx-james) john , friend 3(unknown name xxx-james) james fred). 

the names within smallest () matched john or james , substituted non-greedy pattern.

i tried perl, failed desired output.

if strings you're working simple sample input , output, i'd you're making harder is. can search "john)" , "james)", so:

$ echo "this 1(the house owner 2(pet-name john) john , friend 3(unknown name james) james fred)" | sed -r 's/(john\)|james\))/xxx-\1/g' 1(the house owner 2(pet-name xxx-john) john , friend 3(unknown name xxx-james) james fred) 

since mentioned non-greedy patterns, have feeling there more example shows. so, let's pretend don't know if there closing parenthesis right after names:

$ echo "this 1(the house owner 2(pet-name john ok) john , friend 3(unknown name james test) james fred)" | sed -r 's/(\([^()]*)(john|james)([^()]*\))/\1xxx-\2\3/g' 1(the house owner 2(pet-name xxx-john ok) john , friend 3(unknown name xxx-james test) james fred) 

the first set of parentheses captures after (and including) literal opening parenthesis that isn't opening or closing parenthesis until hits "james" or "john".

the second set of parentheses captures "john" or "james".

the third set of parentheses captures after "james" or "john" that isn't opening or closing parenthesis until hits literal closing parenthesis.

this global replacement, work no matter how many sets of parentheses have. can nest them deeper, , apply smallest set.

greediness doesn't come play in situation, if project you're working on, add question mark (e.g. * becomes *?) make non-greedy.


Comments

Popular posts from this blog

download - Firefox cannot save files (most of the time), how to solve? - Super User

windows - "-2146893807 NTE_NOT_FOUND" when repair certificate store - Super User

sql server - "Configuration file does not exist", Event ID 274 - Super User