Jenkins如何提取命令输出每行首个空格前内容并拼接为单行?
两种可行的实现方案:命令行处理或Jenkins Groovy原生处理
你有两种靠谱的方式实现需求,选哪种取决于你的场景偏好:
一、在命令行中直接处理输出(更高效)
直接在执行some command时,通过shell工具把输出处理成目标格式,不用把原始输出拿到Groovy里再二次处理。示例代码:
script { def command_output = sh(returnStdout: true, script: """some command | awk '{print \$1}' | tr '\\n' ' '""").trim() def command_output_two = sh(returnStdout: true, script: """some_other_command ${command_output}""").trim() }
awk '{print $1}':提取每行首个空格前的内容tr '\n' ' ':把换行符替换成空格,拼成单行- 最后用
.trim()去掉首尾多余的空格
如果你的运行环境里awk不太方便,也可以用sed替代:
def command_output = sh(returnStdout: true, script: """some command | sed 's/ .*//' | tr '\\n' ' '""").trim()
sed 's/ .*//'的作用是删除每行第一个空格及之后的所有内容。
二、用Jenkins Groovy原生方法处理(更灵活)
如果不想依赖shell工具的兼容性,或者后续还要对提取的内容做更多逻辑处理,可以把原始输出拿到Groovy里,用字符串方法处理:
script { def raw_output = sh(returnStdout: true, script: """some command""").trim() // 处理输出:按换行拆分→取每行第一个空格前的内容→拼接成单行 def command_output = raw_output.split('\\n') .collect { line -> // 处理可能的空行,避免数组越界 line.trim() ? line.split(' ')[0] : '' } .findAll { it } // 过滤空字符串 .join(' ') def command_output_two = sh(returnStdout: true, script: """some_other_command ${command_output}""").trim() }
这种方式的好处是不依赖系统环境的shell工具,逻辑完全在Groovy层面可控,适合跨平台场景。
内容的提问来源于stack exchange,提问作者Sven van den Boogaart
相关产品推荐
相关产品推荐

