如何在Groovy及Jenkins流水线中用#替换文件换行符
Alright, let's cover both standalone Groovy usage and Jenkins Pipeline implementation for replacing all newline characters (\n) with # in a text file. Here's how you can do it:
For a standalone Groovy script, this is pretty straightforward. The script reads the entire file content, handles the replacement, and writes the modified text back (either to a new file or overwriting the original):
// Define your file paths def inputPath = "/path/to/your/source/file.txt" def outputPath = "/path/to/your/destination/file.txt" // Use inputPath here to overwrite the original // Read the full file content into a string def fileContent = new File(inputPath).text // Replace all newlines with # — use /\r?\n/ to handle Windows-style \r\n line endings too def modifiedContent = fileContent.replaceAll(/\n/, "#") // Write the updated content to the output file new File(outputPath).write(modifiedContent)
A quick note: If your file uses Windows line endings (\r\n), swap the regex to /\r?\n/—this will catch both \n and \r\n to ensure all line breaks get replaced.
In Jenkins, you'll typically work with files in the job's workspace. You have two solid options here: using pure Groovy (cross-OS compatible) or shell/PowerShell commands (great if you prefer those tools).
Option 1: Pure Groovy in a Script Block
This approach works the same across Linux, Windows, and macOS agents:
pipeline { agent any stages { stage('Replace Newlines in File') { steps { script { // Target the file in your Jenkins workspace def targetFile = new File("${WORKSPACE}/your-file.txt") // Read, replace, and write back def updatedContent = targetFile.text.replaceAll(/\r?\n/, "#") targetFile.write(updatedContent) } } } } }
Option 2: Shell/PowerShell Commands
If you're more comfortable with shell tools, this might feel more intuitive:
For Linux/macOS Agents
pipeline { agent any stages { stage('Replace Newlines via Shell') { steps { sh ''' # Replace all newlines with # (handles \n and \r\n) sed -i 's/\\n/#/g' "${WORKSPACE}/your-file.txt" ''' } } } }
For Windows Agents
Use PowerShell instead:
pipeline { agent any stages { stage('Replace Newlines via PowerShell') { steps { powershell ''' # Read the file as a single string, replace newlines, then write back (Get-Content "${env:WORKSPACE}\\your-file.txt" -Raw) -replace "`n", "#" | Set-Content "${env:WORKSPACE}\\your-file.txt" ''' } } } }
Just remember: ${WORKSPACE} is Jenkins' built-in variable pointing to the job's workspace directory, so adjust the file path if your target file is in a subfolder.
内容的提问来源于stack exchange,提问作者DevOops

