Issue
I have a SQL file with the following approximate structure.
INSERT INTO asdassd (3,_binary 'asdfsdfsdf\"/>',-1234);
INSERT INTO hfhdfghdf (1476,'ghdfsdfg','sdfgdfgsdf',-1234);
INSERT INTO retfdxfsd (1476,'xdfgthb',_binary 'nghfghgfh',-1234);
I need to replace the text ',
with '),
on the lines where the word _binary
appears, but only the first occurrence after _binary
.
I have come up with this expression that works correctly for the first two lines but not for the third since it replaces the first occurrence of what I want to replace regardless of the position of the word _binary
.
sed -i "/_binary/{s/',/'),/}" file
Solution
You want to include the condition in the replacement regex.
By the way, the braces in yoqr attempt were unnecessary. Also, probably don't use -i
until you have a working script.
sed -i "s/\(_binary.*\)',/\1'),/" file
In other words, we capture _binary
followed by anything followed by the pattern you want to match, and replace the matching expression with the captured string followed by the replacement. \1
is a backreference which recalls whatever text the first set of capturing parentheses matched.
Answered By - tripleee Answer Checked By - Candace Johnson (WPSolving Volunteer)