问题描述
如何使用sed查找字符串,并在该字符串之后添加另一个文件中的文本?
How can I use sed to locate a string, and add text from another file after the string?
文件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/
I want to be able to use sed to read the second file, and add the contents of each line from the second file after each occurance of 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替换,但是我不知道如何通过读取另一个文件来进行替换.
Can this be done with sed? I'm having issues reading it from a list file and it's confusing since it has a lot of slashes in it. I've been able to use normal sed substitution but I don't know how to do substitution by reading another file.
推荐答案
这是一个bash
脚本,它使用sed
并逐行读取File_2(包含替换项的文件),从而一次读取一个替换项.然后,我用sed脚本替换了File_1中的行.
This is a bash
script that uses sed
and reads File_2 (The file containing the replacements) line by line, thus reading one replacement at a time. I then replaced the lines in File_1 with a sed script.
while IFS= read -r line; do
sed -i "0,/\/stash\/scm\/'/{s|/stash/scm/'|/stash/scm/${line}'|}" File_1.txt
done < File_2.txt
用于完成此操作的一些技巧:
Some tricks used to do this:
-
sed '0,/Apple/{s/Apple/Banana/}' input_filename
仅将字符串Apple
的文件名中的 first 出现替换为字符串Banana
- 对
sed
脚本使用双引号,以允许变量扩展${line}
- 确保要替换的搜索字符串在每次迭代中都已更改.这是通过在sed脚本
s|/stash/scm/'|
中为搜索参数包含结尾的单引号char - 在bash脚本中逐行读取文件
'
来完成的.sed '0,/Apple/{s/Apple/Banana/}' input_filename
Replace only the first occurrence in filename of the stringApple
with the stringBanana
- Using double quotes for the
sed
script to allow for variable expansion${line}
- Making sure the search string to replace was being changed each iteration. This was done by including the ending single quote char
'
for the search argument in the sed scripts|/stash/scm/'|
- Reading a file line by line in a bash script
while IFS= read -r line; do
echo $line
done < File_2.txt
这篇关于使用sed在模式之后添加文本,但是添加的文本来自列表文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!