The reaction you're describing is known as a macrolactonisation, where a medium/large ring is closed by the formation of an lactone (a cyclic ester).
The real problem with macrolactonisation is that there is a somewhat significant entropic barrier to the reaction, you're taking something with a lot of flexibility and constraining it into a ring, reducing the conformational flexibility of the system. As the ring size increases, entropy becomes significantly more important than enthalpy.
Because the reaction is so entropically unfavourable, the intermolecular reaction has a tendency of happening (rather than the desired intramolecular ring closure).
To avoid these issues, two things are commonly done:
- macrolactonisations are ran with high dilution, high dilution favours the intramolecualar reaction by decreasing the probability of two molecules encountering one another
- modern macrolactonisation procedures limit the amount of the activated carboxylic acid present (or indeed the activated alcohol) at any one time, again, preventing the likelihood of two molecules reacting together in an intermolecular sense.
The whole thing is maybe easiest explained with an example. The Yamaguchi macrolaconisation is one of the most common, but many others (i.e. the Shiina) follow the same principle.
In the first step, the seco acid (the molecule with the free OH and the free carboxylic acid) are reacted with the TCBC to form a mixed anhydride.
Although this mixed anhydride is 'activated' relative to the free carboxylic acid, it isn't usually reactive enough, meaning that the mixed anhydride can be isolated (no intra or intermolecular reaction takes place).
The isolated mixed anhydride is then added dropwise to a very dilute solution of DMAP (acting as a nucleophilic catalyst). The DMAP attacks the mixed anhydride, forming a highly reactive intermediate (much more reactive than the mixed anhydride), from which the alcohol may attack the carbonyl, displacing DMAP, and forming the desired macrolactone. By adding the mixed anhydride to the DMAP, it limits the amount of the molecule in the flask which is sufficiently activated to react at any given time, increasing the likelihood of intramolecular reaction further.