Issue
How can I use sed to locate a string, and add text from another file after the string?
File 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 *
"""
}
}
File 2:
randomRepo.git
differentRandomRepo.git
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/
Desired output:
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 *
"""
}
}
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.
Solution
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
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
Read File line by line in bash
Answered By - Lenna
Answer Checked By - Mary Flores (JavaFixing Volunteer)