简体   繁体   English

具有动态变量和空格的 sed 命令 - 不保留空格

[英]sed command with dynamic variable and spaces - not retaining spaces

I am trying to insert a variable value into file from Jenkinsfile using shell script in the section Variable value is dynamic.我正在尝试使用变量值是动态部分中的 shell 脚本将变量值从 Jenkinsfile 插入文件。 I am using sed.我正在使用 sed。

Sed is working fine but it is not retaining the white spaces that the variable have at the beginning. Sed 工作正常,但它没有保留变量在开始时具有的空格。

ex: The value of >> repoName is " somename"例如:>> repoName 的值为“somename”

stage('trying sed command') {
      steps {
        script {
          sh """
          #!/bin/bash -xel
          repo='${repoName}'
          echo "\$repo"
          `sed -i "5i \$repo" filename`
          cat ecr.tf
          """
        }
      }
    }

current output:电流输出:

names [
   "xyz",
   "ABC",
somename
   "text"
 ]

Expected output:预期输出:

names [
   "xyz",
   "ABC",
   somename
   "text"
 ]

How do i retain the spaces infront of the variable passing from sed我如何保留从 sed 传递的变量前面的空格

With

$ cat filename
names [
   "xyz",
   "ABC",
   "text"
 ]

$ repo=somename

we can do:我们可以做的:

sed -E "3s/^([[:blank:]]*).*/&\\n\\1${repo},/" filename
names [
   "xyz",
   "ABC",
   somename,
   "text"
 ]

That uses capturing parentheses to grab the indentation from the previous line.这使用捕获括号来获取上一行的缩进。


if $repo might contain a value with slashes, you can tell the shell to escape them with this (eye-opening) expansion如果$repo可能包含一个带有斜杠的值,你可以告诉 shell 用这个(大开眼界的)扩展来转义它们

repo='some/name'
sed -E "3s/^([[:blank:]]*).*/&\\n\\1${repo//\//\\\/},/" filename
names [
   "xyz",
   "ABC",
   some/name,
   "text"
 ]

I used 1 sed statement to add the content first to the file and then another sed statement for just adding spaces.我使用 1 个 sed 语句首先将内容添加到文件中,然后使用另一个 sed 语句来添加空格。 This fixed my issue.这解决了我的问题。 All day i was trying to fit in one command did not work probably from Jenkins and shell usage.一整天我都在尝试适应一个命令,这可能是由于 Jenkins 和 shell 的使用而无法工作。 But using 2 sed commands as a workaround i was able to finish my task但是使用 2 个 sed 命令作为解决方法,我能够完成我的任务

The i command skips over spaces after the i command to find the text to insert. i命令跳过i命令后的空格以查找要插入的文本。 You can put the text on a new line, with a backslash before the newline, to have the initial whitespace preserved.您可以将文本放在新行上,在换行符之前使用反斜杠,以保留初始空白。

stage('trying sed command') {
      steps {
        script {
          sh """
          #!/bin/bash -xel
          repo='${repoName}'
          echo "\$repo"
          `sed -i "5i \\\\\\
\$repo" filename`
          cat ecr.tf
          """
        }
      }
    }

I've tested this from a regular shell command line, I hope it will also work in the Jenkins recipe.我已经从常规的 shell 命令行对此进行了测试,我希望它也可以在 Jenkins 配方中使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM