I have the following function:
function DivideAndCreateFiles ([string] $file, [string] $ruleName) {
$Suffix = 0
$FullData = Get-Content $file
$MaxIP = 40
while ($FullData.count -gt 0 ){
$NewData = $FullData | Select-Object -First $MaxIP
$FullData = $FullData | Select-Object -Skip $MaxIP
$NewName = "$ruleName$Suffix"
New-Variable -name $NewName -Value $NewData
Get-Variable -name $NewName -ValueOnly | out-file "$NewName.txt"
$Suffix
}
}
This function takes a file location, this file holds hundreds of ips. it then iterate the file and create files from it each one holding 40 ip's naming it $rulename$suffix so if $rulename=blabla
i would get blabla_0 , blabla_1, .. and so on, each with 40 ips.
i need to convert this logic and put it inside a jenkins job. this file is in the working dir of the job and is called ips.txt
suffix = 0
maxIP = 40
ips = readFile('ips.txt')
...
Id be very happy for some help here re-writing this function, im very new to jenkins / groovy
Thanks in advacne
CodePudding user response:
You can achieve this easily using something like the following groovy code:
def divideAndCreateFiles(path, rule_name, init_suffix = 0, max_ip = 40){
// read the file and split lines by new line separator
def ips = readFile(path).split("\n").trim()
// divide the IPs into groups according to the maximum ip range
def ip_groups = ips.collate(ips.size().intdiv(max_ip))
// Iterate over all groups and write them to the corresponding file
ip_groups.eachWithIndex { group, index ->
writeFile file : "${rule_name}${init_suffix index}", text: group.join("\n")
}
}
From my perspective, because you are already writing a full pipeline in groovy, it is easier to handle all logic in groovy, including this function.
CodePudding user response:
This is not an answer about converting to Jenkins, but a re-write of your original PowerShell function, which splits a file in a very inefficient way.
(can't do that in a comment)
This utilizes the -ReadCount
parameter of Get-Content
, which specifies how many lines of content are sent through the pipeline at a time.
Also, I have renamed the function to comply to the Verb-Noun naming recommendations.
function Split-File ([string]$file, [string]$ruleName, [int]$maxLines = 40) {
$suffix = 0
$path = [System.IO.Path]::GetDirectoryName($file)
Get-Content -Path $file -ReadCount $maxLines | ForEach-Object {
$_ | Set-Content -Path (Join-Path -Path $path -ChildPath ('{0}_{1}.txt' -f $ruleName, $suffix ))
}
}