Willy Churchill leaves a Rite Aid store in Oakland, California. Reuters/Noah Berger

Walgreens Boots Alliance announced on Thursday that it entered into an agreement to acquire 2,186 Rite Aid stores and related assets for $5.18 billion in cash.

It's the latest twist in the ongoing saga between the two companies, which drew scrutiny from US antitrust regulators earlier this year after announcing a merger valued at $17.2 billion back in October 2015. The deal would've seen Walgreens acquire all outstanding shares of Rite Aid. The new deal will replace the original merger agreement.

As part of the termination, Walgreens will pay Rite Aid a fee of $325 million in cash.

Rite Aid's stock plunged by 20% in premarket trading following the announcement after spiking by as much as 23% earlier. Walgreens saw shares climb by 4.2%.

The asset sale will reposition Rite Aid as an independent, multiregional drugstore chain and pharmacy benefits manager, according to a press release from the company. Rite Aid will also have the option to buy generic drugs from an affiliate of Walgreens.

Further, Rite Aid is expected to use the proceeds from the deal to "significantly" reduce debt and strengthen its balance sheet, the release said.

"While we believe that pursuing the merger with WBA was the right thing to do for our investors and customers, this new agreement provides a clear path forward," Rite Aid chairman and CEO John Standley said in a statement. "The transaction offers clear solutions to assist us in addressing our pharmacy margin challenges and allows us to significantly reduce debt."

The deal also terminates a divestiture agreement that Rite Aid had previously made with Fred's that would have seen the Tennessee-based pharmacy chain acquire 865 Rite Aid stores for $950 million in cash, but only after merger with Walgreens closed.

The board at Fred's sensed something was amiss with the original merger on Wednesday following some "increased trading activity," and elected to adopt a short-term shareholder rights plan, or "poison pill." The company's stock plummeted by 18% in premarket trading.

The new deal overshadowed Rite Aid's first-quarter 2018 earnings report, which saw both revenue and adjusted EBITDA miss consensus analyst estimates. The results also came in below the most bearish forecast for either measure.