bash - 将子字符串添加到bash中的字符串
问题描述
我有以下数组:
SPECIFIC_FILES=('resources/logo.png' 'resources/splash.png' 'www/img/logo.png' 'www/manifest.json')
以及以下变量:
CUSTOMER=default
如何遍历我的数组并生成看起来像的字符串
resources/logo_default.png
取决于变量。
解决方案
下面使用参数扩展来提取相关子字符串,如BashFAQ #100中所述:
specific_files=('resources/logo.png' 'resources/splash.png' 'www/img/logo.png' 'www/manifest.json')
customer=default
for file in "${specific_files[@]}"; do
[[ $file = *.* ]] || continue # skip files without extensions
prefix=${file%.*} # trim everything including and after last "."
suffix=${file##*.} # trim everything up to and including last "."
printf '%s\n' "${prefix}_$customer.$suffix" # concatenate results of those operations
done
此处使用小写变量名称以符合POSIX 指定的约定(全大写名称用于对操作系统或 shell 有意义的变量,而具有至少一个小写字符的变量保留供应用程序使用;设置常规 shell 变量会覆盖任何类似命名的环境变量,因此约定适用于这两个类)。
推荐阅读
- php - 如何在magento2中阻止礼品卡页面的货币切换器
- node.js - 用于自动完成的 VS 代码 npm 扩展对我不起作用
- c# - 使用 TestServer 进行 ASP.net 核心集成测试有什么优势?
- html - 修复了使用带有伪元素的 CSS 网格的纵横比网格布局在 Safari 或 Firefox 中不起作用
- c# - 将 VB.NET 委托转换为 C#
- c++ - 使用类的构造函数时出错
- c# - 我的 webrequest 不工作得到 400 错误消息?
- python - Asyncpg“$1 或附近的语法错误”错误
- sql - 哪种方法更好地在嵌套数组或普通数组上搜索关键字?
- javascript - 使用 JS 从 firebase 获取数据并放入对象