首页 > 解决方案 > 用列表文件中的每一行替换每个出现的单词

问题描述

我想在下面的代码中命名每个 .tar 文件,并根据包含名称的列表文件对其进行命名,但我不想弄乱排除标记。我有一个列表文件,我正在考虑使用文本编辑器并将 cvf 添加到列表中每一行的开头,然后使用 sed 替换字符串cvf,从而添加标志,然后是名称。

IE cvf name1 cvf name2 cvf name3

我尝试使用sed 's/cvf/word2/g' input.file,并且正如预期的那样,它只用替换词替换了 cvf。我希望替换词(word2)改变并成为列表文件中的每一行。

我要修改的代码: stage ('Zip Repo340') { steps { sh""" tar --exclude='*.tar' -cvf .tar * """ stage ('Zip Repo341') { steps { sh""" tar --exclude='*.tar' -cvf .tar * """ stage ('Zip Repo342') { steps { sh""" tar --exclude='*.tar' -cvf .tar * """

我有 340 个这样的存储库,我想根据我拥有的列表文件来命名它们。

清单文件:

name1 name2 name3

期望的输出:

stage ('Zip Repo340') { steps { sh""" tar --exclude='*.tar' -cvf name1.tar * """ stage ('Zip Repo341') { steps { sh""" tar --exclude='*.tar' -cvf name2.tar * """ stage ('Zip Repo342') { steps { sh""" tar --exclude='*.tar' -cvf name3.tar * """

我可以将 cvf 添加到列表文件的每一行,但如果有更优雅的解决方案,我会全力以赴。我遇到的最大问题是运行 sed 替换命令并让替换词来自列表文件。

标签: regexlinuxbashsed

解决方案


您可以执行以下操作:

SCRIPT_NAME='outScript.sh'
while read filename; do
  # Replace only the first match:
  sed "0,/-cvf \.tar/s/-cvf \.tar/-cvf ${filename}.tar/" $SCRIPT_NAME > /tmp/tmp.sh
  mv /tmp/tmp.sh $SCRIPT_NAME
done < all_filenames.txt 

基本上,您浏览您的名称文件,并且对于每个名称,您替换第一个未替换的匹配项


推荐阅读