gpt4 book ai didi

linux - 使用 sed 在模式后添加文本,但添加的文本来自列表文件

转载 作者:行者123 更新时间:2023-12-02 07:58:06 25 4
gpt4 key购买 nike

如何使用 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 替换,但我不知道如何通过读取另一个文件来进行替换。

最佳答案

在下文中,我提出了一个几乎纯粹的 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

关于linux - 使用 sed 在模式后添加文本,但添加的文本来自列表文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60874910/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com