regex - 用列表文件中的每一行替换每个出现的单词
问题描述
我想在下面的代码中命名每个 .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 替换命令并让替换词来自列表文件。
解决方案
您可以执行以下操作:
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
基本上,您浏览您的名称文件,并且对于每个名称,您替换第一个未替换的匹配项
推荐阅读
- amazon-web-services - 在 AWS EC2 实例中使用 S3 的 AccessDenied 应用程序
- javascript - 在我的 NextJS API 路由中解析响应数据时遇到问题,一直返回 undefined
- html - 数字标牌 Websocket 控制
- podman - Podman - 如何使用 Podman 3.0 维护秘密
- swift - 为什么是 UIImage?这里没有?
- python - 是否有 python 函数来获取 json 数据的组合?
- amazon-web-services - 使用无服务器框架部署时,从 Codebuild 构建规范的第一行中删除了新行
- unit-testing - 有没有办法在给定的时间后使单元/集成测试失败?
- angular - 我想在我的角度应用程序中有一个带有标签的子菜单
- java - 如何在滚动期间停止更改回收站视图中的项目数据