Do we have a script to discard old build and keep max build#5 in jenkins

Hello Jenkins Community,
Current I have few 100 Jenkins build jobs running in Jenkins. I’m looking is there a way instead of adding going to individual job and add enabling discard build and set max build #5 , is there a script which I can test where in I can add for individual job the policy is enable autimatically.

I tried with this script and added in script console , but failed.

// Jenkins job
def jobName = 'foo'
// Range of builds to delete
def rs = Fingerprint.RangeSet.fromString("0-3", false);
// Set to true to actually delete. Use false to test the script.
def reallyDelete = false;

// ----------------------------------
def job = Jenkins.instance.getItemByFullName(jobName);
println("Job: ${job.fullName}");

def builds = job.getBuilds(rs);
println("Found ${builds.size()} builds");
builds.each{ b-> 
  if (reallyDelete) {
    println("Deleting ${b}");
    b.delete();
  } else {
    println("Found match ${b}");
  }
}

Appreciate for inputs or simple script which I can test.

Build Discarder does exactly what you want.

Appreciated Hlemeur for quick reply.
where can I apply the changes in Script console or in my script?

unclassified:
buildDiscarders:
configuredBuildDiscarders:
- “jobBuildDiscarder”
- defaultBuildDiscarder:
discarder:
logRotator:
artifactDaysToKeepStr: “50”
artifactNumToKeepStr: “5”
daysToKeepStr: “100”
numToKeepStr: “10”

Any suggestion and guidance will be appreciated for me to test on few jobs and builds.

My jenkins version is [Jenkins 2.332.2] and Build Discarder shows for Jenkins 2.346.1
So how can I integrated in my script, any thoughts?

If you want to apply a configuration change to many different jobs at the same time, you might consider the configuration slicing plugin. It allows a configuration change to be applied to many jobs at the same time

You should plan your upgrade from that version to a recent release and should plan to regularly upgrade to recent releases . The Jenkins update center no longer provides data for that version. It contains known vulnerabilities.