本文介绍了使用sed在模式之后添加文本,但是添加的文本来自列表文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用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:

  1. sed '0,/Apple/{s/Apple/Banana/}' input_filename仅将字符串Apple文件名中的 first 出现替换为字符串Banana
  2. sed脚本使用双引号,以允许变量扩展${line}
  3. 确保要替换的搜索字符串在每次迭代中都已更改.这是通过在sed脚本s|/stash/scm/'|
  4. 中为搜索参数包含结尾的单引号char '来完成的.
  5. 在bash脚本中逐行读取文件
  1. sed '0,/Apple/{s/Apple/Banana/}' input_filename Replace only the first occurrence in filename of the string Apple with the string Banana
  2. Using double quotes for the sed script to allow for variable expansion ${line}
  3. 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 script s|/stash/scm/'|
  4. Reading a file line by line in a bash script
while IFS= read -r line; do
    echo $line
done < File_2.txt

逐行读取文件在bash中

这篇关于使用sed在模式之后添加文本,但是添加的文本来自列表文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 14:41