首页 > 解决方案 > 将子字符串添加到bash中的字符串

问题描述

我有以下数组:

SPECIFIC_FILES=('resources/logo.png' 'resources/splash.png' 'www/img/logo.png' 'www/manifest.json')

以及以下变量:

CUSTOMER=default

如何遍历我的数组并生成看起来像的字符串

resources/logo_default.png

取决于变量。

标签: bash

解决方案


下面使用参数扩展来提取相关子字符串,如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 变量会覆盖任何类似命名的环境变量,因此约定适用于这两个类)。


推荐阅读