The sale of five Steward Health Care hospitals in Massachusetts was approved by a federal bankruptcy court judge Wednesday, ending doubts of whether the beleaguered medical centers could have a chance to stay open.

Lawrence General Hospital was approved to buy Holy Family Hospital in Methuen and Haverhill; Lifespan Health System, a Rhode Island-based company, can purchase St. Anne’s Hospital in Fall River and Morton Hospital in Taunton; and Boston Medical Center can buy St. Elizabeth’s Medical Center in Brighton and Good Samaritan Hospital in Brockton under the plan approved by Judge Christopher Lopez, with the caveat that the sales must happen by Sept. 30, or the buyers can back out.

“There are real people in these hospitals right now,” Lopez said. “The sale needs to happen, and it will happen.”

The company also received approval for another round of financial support from the state: an infusion of $42 million to help hospitals make payroll and pay bills in September before new owners take over. The state already gave the company $30 million for August operations.

The $343 million deal wasn’t ideal for everyone. Lenders that had helped finance Steward’s bankruptcy objected to it and argue they’re owed funds.

“We don’t want this sale to blow up unless it absolutely has to,” said Michael Price, an attorney for the lenders. He said they shouldn’t be asked to accept “zero dollars,” a plea reflected in Lopez’s decision. The judge will withhold $17 million — the exact amount of Steward’s “funding shortfall”— to give himself more time to consider lenders’ arguments.

The Healey administration and federal government had attorneys present who testified in support of the sales. The purchases are still subject to regulatory reviews, which can be expedited. Two Steward-owned hospitals closed on Saturday — Nashoba Valley Medical Center in Ayer, and Carney Hospital in Dorchester — after Steward couldn’t find qualified bids for the facilities.