Ghana led twice in a seesaw thriller at the Cairo International Stadium before ex-Stoke City and Huddersfield Town attacker Sobhy levelled on 82 minutes.
With two minutes of regular time remaining, Sobhy swung a corner into the heart of the goalmouth and Ahmed Rayan headed powerfully into the net for a dramatic victory.
Captain Yaw Yeboah had given Ghana a sixth-minute lead that Egyptian wonder boy Mostafa Mohamed cancelled on 17 minutes with his second goal of the Olympics qualifying tournament.
A weak back pass from Mohamed Abdelsalam allowed Samuel Obeng to put Ghana ahead again just one minute into the second half as he went past goalkeeper Mohamed Sobhy and tapped in.
Stung by falling behind a second time, Egypt attacked relentlessly and had what they believed was a 57th-minute equaliser disallowed with replays showing Sobhy was marginally offside.
The victory lifted Egypt to six points in Group A from two matches after they defeated Mali in the tournament opener last Friday.
Cameroon, who beat Mali 1-0 in the first match of a double-header, are second with four points followed by Ghana with one while pointless Mali have been eliminated.
Egypt will finish first provided they avoid losing to Cameroon Thursday while Ghana must defeat Mali and hope Cameroon lose to have a chance of reaching the semi-finals.
Franck Evina, who is on the books of European giants Bayern Munich and known as the 'Bavarian Hulk', scored the 76th-minute goal that defeated Mali.
Mali failed to clear a Olivier Mbaizo cross and Evina netted for the second successive match with a clinical finish that gave goalkeeper Koita Youssouf no chance.
The countries finishing first, second and third will represent Africa in Tokyo and try to emulate gold medal winners Nigeria (1996) and Cameroon (2000).
Olympic qualifiers are restricted to under-23 footballers, but three 'over-age' players are permitted at the finals.