Bamidbar31:2

נְקֹם נִקְמַת בְּנֵי יִשְׂרָאֵל מֵאֵת הַמִּדְיָנִים אַחַר תֵּאָסֵף אֶל־עַמֶּיךָ׃

"Avenge the children of Israel on the Midyanites. Afterward you shall be gathered to your people."

Bamidbar 31:2

נְקֹם נִקְמַת בְּנֵי

Bamidbar / Numbers 31:2 · Pshat

Bamidbar 31:2

נְקֹם נִקְמַת בְּנֵי יִשְׂרָאֵל מֵאֵת הַמִּדְיָנִים אַחַר תֵּאָסֵף אֶל־עַמֶּיךָ׃

"Avenge the children of Israel on the Midyanites. Afterward you shall be gathered to your people."

Pshat פְּשָׁט

Moshe's last task

A person is told: do this, and after it your life will end. Someone else would drag it out. The commentators explain why Moshe (Moses) is given this very task.

Rashi: vengeance is taken on the Midyanites, not the Moabites, since Moav acted out of fear while Midyan meddled in a quarrel not its own, and from Moav Rut will come. Ramban: Moshe will not enter the land, but on this side of the Yarden (Jordan) he fulfils all the commandments, and he is given the honour of seeing the vengeance before he dies. Pinchas (Phinehas) leads the war: he began the deed, and he should finish it.

How Rashi and Ramban explain it

Rashi From the Midyanites

And not from the Moabites, because the Moabites entered into the matter out of fear: they were afraid that Israel would plunder them, for of them it was said only "do not contend with them in battle" (Devarim / Deuteronomy 2:9). But the Midyanites meddled in a quarrel that was not theirs. Another explanation: because of two good doves that I am to bring out of them: Rut the Moabite and Naamah the Ammonite.

Ramban Avenge the children of Israel, afterward you shall be gathered to your people

It was decreed on Moshe (Moses) our teacher that he would not cross the Yarden (Jordan), but on that side of the Yarden he fulfilled all the commandments of Israel: he defeated the two great kings of the Emorites and divided their land as an inheritance. And it was fitting for him to execute vengeance on the enemies of the Eternal, while on Yehoshua (Joshua) are only the commandments of the land itself. And further: the Holy One, blessed is He, granted him this honour, that he should see and rejoice, as "the righteous shall rejoice when he sees vengeance" (Tehillim / Psalms 58:11). That is the meaning of "afterward you shall be gathered to your people". And Moshe granted honour to Pinchas (Phinehas): he began the commandment, and it is his to finish, and Moshe made him the anointed one for this war. And it was not fitting for Elazar (Eleazar) to go, for he is the high priest.

Takeaway

Rut the Moabite is the great-grandmother of King David (Rut / Ruth 4:17). Naamah the Ammonite is the mother of King Rechavam, son of Shlomo (Solomon) (Melachim I / I Kings 14:21).
Of Moav the Torah says: "Do not harass Moav and do not contend with them in battle" (Devarim / Deuteronomy 2:9).
Pinchas began this deed when he stopped the plague by killing Zimri and the Midyanite woman Kozbi (Bamidbar / Numbers 25:7–8).