首页 > 解决方案 > 在 Shell 脚本中将字符串转换为数组

问题描述

我对 bash 和 shell 脚本非常陌生。我有一个字符串

string="new string added -value:ABC-10"

现在我想要的是在 -value: 之后获取字符串。

我正在使用 bash 版本 5。尝试过的事情清单

  1. IFS方法,但这是语法错误:重定向意外
  2. array=(${string//:/ }) 这种东西
  3. 同时读取 -r 行;做行+=(“$行”);完成 <<<"$string"
  4. string='巴黎、法国、欧洲'; readarray -td, 一个 <<<"$string"; 声明-pa;

除了 IFS 之外,其他所有解决方案都给出了语法错误“(”预期的“}”,我已经尝试了所有可能的组合,但没有运气。

任何帮助表示赞赏。

提前致谢。

标签: arraysstringbashshell

解决方案


这是直接使用 bash。试一试:

printf "%s\n"  "${string##*-value:}"

bash

  ${parameter#word}
  ${parameter##word}
         Remove matching prefix pattern.  The word is expanded to produce a pattern just as in pathname expansion, and matched against the expanded value of parameter using the rules  described  under
         Pattern Matching below.  If the pattern matches the beginning of the value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern
         (the ``#'' case) or the longest matching pattern (the ``##'' case) deleted.  If parameter is @ or *, the pattern removal operation is applied to each positional parameter in turn, and the ex‐
         pansion  is  the resultant list.  If parameter is an array variable subscripted with @ or *, the pattern removal operation is applied to each member of the array in turn, and the expansion is
         the resultant list.

推荐阅读