首页 > 解决方案 > 使用 sed 在模式后添加文本,但添加的文本来自列表文件

问题描述

如何使用 sed 定位字符串,并在字符串后添加另一个文件中的文本?

文件 1:

stage ('Clone Repo31') {

        steps {
                git credentialsId: '', url: '/stash/scm/'
        }
    }
    stage ('Zip Repo31') {
        steps {
        sh"""
            tar --exclude='*.tar' -cvf .tar *
        """
        }
    }
    steps {
            git credentialsId: '', url: '/stash/scm/'
    }
}
stage ('Zip Repo32') {
    steps {
    sh"""
        tar --exclude='*.tar' -cvf .tar *
    """
    }
}

文件 2:

randomRepo.git
differentRandomRepo.git

我希望能够使用 sed 读取第二个文件,并在每次出现 stash/scm/ 后添加第二个文件中每一行的内容

期望的输出:

       stage ('Clone Repo31') {

        steps {
                git credentialsId: '', url: '/stash/scm/randomRepo.git'
        }
    }
    stage ('Zip Repo31') {
        steps {
        sh"""
            tar --exclude='*.tar' -cvf .tar *
        """
        }
    }
    steps {
            git credentialsId: '', url: '/stash/scm/differentRandomRepo.git'
    }
}
stage ('Zip Repo32') {
    steps {
    sh"""
        tar --exclude='*.tar' -cvf .tar *
    """
    }
}

这可以用sed完成吗?我在从列表文件中读取它时遇到问题,这很令人困惑,因为它有很多斜杠。我已经能够使用正常的 sed 替换,但我不知道如何通过读取另一个文件来进行替换。

标签: linuxbashjenkinssedterminal

解决方案


在下文中,我提出了一个几乎纯正的sed解决方案。

sed有一个r读取文件的命令,因此您原则上可以使用它来读取file2. 但是,没有后续命令会影响从文件中读取的行,因此我想不出任何r有效地使用该命令来完成您所要求的操作的方法。

但是,如果file1file2都在 的输入中给出,则解决方案是可能的sed

下面,为了区分这两个文件,我打了一个标记线(-----),我理所当然地认为不在file2;然而,它可以在任何地方file1而不会产生任何问题。

cat file2 <(echo '-----') file1 | sed -f script.sed

以下内容在哪里script.sed

1{                     # only on line 1
  :a                   # begin while
  /-----/!{            # while the line does not contain the marker
    N                  # append the following line
    ba                 # end while
  }                    # here the pattern space is a multiline containing the list
  s/\n-----//          # remove the last newline and the marker
  h                    # put the multiline in the hold space
  d                    # delete, as we don't want to print anything so far
}                      # that's it, lines from 1 to the marker are processed
/stash\/scm\//{        # for lines matching this pattern
  G                    # we append the full hold space
  s/'\n\([^\n]*\)/\1'/ # and position the first entry in the list appropriately
  x                    # then we swap pattern and hold space
  s/[^\n]*\n//         # remove the first element of the list
  x                    # and swap again
}                      # now the hold space has one item less

推荐阅读