SAO PAULO, May 21 (Reuters) - Brazilian beef producer Marfrig Global Foods SA said on Friday it had bought almost a quarter of BRF SA's outstanding shares and aimed to diversify its holdings rather than influence management.

Marfrig bought up the 24% stake in BRF, the world's largest poultry exporter that also processes pork, spending what a source familiar with the matter said was about $800 million. The transaction comes almost two years after previous failed merger talks between the two companies.

But Marfrig said it would be only a passive investor with no representation on BRF's board, and it took the stake to diversify its investments "in a segment which complements the sector where it does business."

The two companies' portfolios could be complementary if ever combined under one corporate roof given Marfrig's focus on beef and BRF's on poultry and pork.

Marfrig's ability to buy a significant chunk in its larger competitor underlines the strength in its North American division, where consumer demand has been strong and cattle prices relatively low. This has bolstered its stock price relative to BRF, whose margins have been squeezed by its greater reliance on Brazil.

Both companies compete with larger JBS SA, which boasts a diversified production base and sales of processed foods and three protein types. While BRF has most of its plants in Brazil, Marfrig sells beef here and in North America, where it gets the lion's share of its revenue.

Brazilian meatpackers have seen profits surge in recent years, helped by strengthening demand from China, especially starting in 2018, when a deadly pig disease forced it to cull millions of animals, making room for more imports from the likes of BRF and Marfrig.

But they have also faced sharply higher costs lately as cattle prices soared and grain costs hit record highs, threatening to devour profit margins.

The companies had discussed a potential takeover of BRF by Marfrig, but broke off talks in July 2019.

BRF shares accelerated their rise on the news, gaining more than 16% on Friday afternoon in Sao Paulo. Marfrig shares fell about 3%.

JPMorgan Chase & Co advised Marfrig on the deal, according to a source speaking on condition of anonymity.

Marfrig's stake-building in BRF was first reported by newspaper Valor Econômico.

(Reporting by Tatiana Bautzer and Ana Mano; Additional reporting by Carolina Mandl; Editing by David Gregorio and Stephen Coates)