将Bash函数参数分隔符作为字符串数组拆分。

huangapple go评论50阅读模式
英文:

Delimiter to split Bash function arguments as an array of strings

问题

对于一个 Bash 函数 my_fun,如何使用分隔符(例如 ";")来将输入分割成字符串数组?

示例输入:

$ my_fun This is ; an example

示例输出:

string1: This is
string2: an example

也许可以使用 $IFS=';'read 命令?

英文:

For a Bash function my_fun, how can I use a delimiter (e.g. ";") to split input into an array of strings?

Example input:

$ my_fun This is ; an example

Example output:

string1: This is
string2: an example

Perhaps using $IFS=';' or the read command?

答案1

得分: 2

分隔符;需要用反斜杠(\;)转义,以防止Bash将其解释为命令分隔符:

my_fun() {
  IFS=\; read -ra arr <<< "$@"
  for i in "${!arr[@]}"; do
    echo "string$i: ${arr[i]}"
  done
}

输出:

$ my_fun This is\;an example
string0: This is
string1: an example
英文:

Delimiter ; needs to be escaped with a backslash (\;) to prevent Bash from interpreting it as a command separator :

my_fun() {
  IFS=&#39;;&#39; read -ra arr &lt;&lt;&lt; &quot;$@&quot;
  for i in &quot;${!arr[@]}&quot;; do
    echo &quot;string$i: ${arr[i]}&quot;
  done
}

Output :

$ my_fun This is\;an example
string0: This is
string1: an example

答案2

得分: 1

这是您的翻译:

借助评论,这是我的解决方案:

```bash
split_str() {
    IFS=";" read -ra arr <<< "$*"
    s1="${arr[0]}"
    s2="${arr[1]}"
    echo "s1: $s1"
    echo "s2: $s2"
}

示例:

$ split_str "This is;a test"
s1: This is
s2: a test

参数应该用引号括起来,因此无论分隔符是shell中的命令分隔符都没有关系。


<details>
<summary>英文:</summary>

With the help of the comments, here&#39;s my solution:

split_str() {
IFS=";" read -ra arr <<< "$*"
s1="${arr[0]}"
s2="${arr[1]}"
echo "s1: $s1"
echo "s2: $s2"
}


Example: 

$ split_str "This is;a test"
s1: This is
s2: a test


The parameters are to be quoted, so it doesn&#39;t matter whether the delimiter is a command separator in the shell.

</details>



# 答案3
**得分**: 0

不需要循环,不需要`read`,只需将数组赋值,`IFS` 设置为`;`:

```bash
my_fun() { IFS=';' arr=( $@ ); printf '|%s|\n' "${arr[@]}"; }
my_fun "foo ; bar ; baz"
|foo |
| bar |
| baz|

正如注释中所指出的,如果输入包含通配符模式(如*),可能会出现问题:路径名展开将应用。如果可能会发生这种情况,可以启用/禁用noglob选项:

my_fun() { set -f; IFS=';' arr=( $@ ); set +f; printf '|%s|\n' "${arr[@]}"; }
英文:

No need to loop, no need to read, simply assign an array with IFS set to ;:

my_fun() { IFS=&#39;;&#39; arr=( $@ ); printf &#39;|%s|\n&#39; &quot;${arr[@]}&quot;; }
my_fun &quot;foo ; bar ; baz&quot;
|foo |
| bar |
| baz|

As noted in comments this may break if the input contains glob patterns (like *): pathname expansion would apply. If this can happen you can enable/disable the noglob option:

my_fun() { set -f; IFS=&#39;;&#39; arr=( $@ ); set +f; printf &#39;|%s|\n&#39; &quot;${arr[@]}&quot;; }

huangapple
  • 本文由 发表于 2023年2月24日 12:01:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/75552506.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定