英文:
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=';' read -ra arr <<< "$@"
for i in "${!arr[@]}"; do
echo "string$i: ${arr[i]}"
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'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'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=';' arr=( $@ ); printf '|%s|\n' "${arr[@]}"; }
my_fun "foo ; bar ; baz"
|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=';' arr=( $@ ); set +f; printf '|%s|\n' "${arr[@]}"; }
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论