简体   繁体   English

Bash有条件地将字符串拆分为数组

[英]Bash conditionally split string into array

I've browsed questions for splitting input based on a character but can't quite figure out multiple characters based on a condition: 我已经浏览了有关根据字符拆分输入的问题,但根据条件无法完全弄清楚多个字符:

Say I had a simply bash script that split input separated by spaces into an array: 假设我有一个简单的bash脚本,它将用空格分隔的输入分割成一个数组:

echo "Terms:"
read terms            // foo bar hello world
array=(${terms// / }) // ["foo", "bar", "hello", "world"]

I want an extra condition where if terms are encapsulated by another character, the whole phrase should be split as one. 我想要一个额外的条件,如果术语由另一个字符封装,则整个短语应拆分为一个。

eg encapsulated with a back tick: 例如,封装有反勾号:

echo "Terms:"
read terms            // foo bar `hello world`
{conditional here}    // ["foo", "bar", "hello world"]

Specify a delimiter other than whitespace for the call to read : 指定非空白的定界符,以使调用read

$ IFS=, read -a array   # foo,bar,hello world
$ printf '%s\n' "${array[@]}"
foo
bar
hello world

You should probably be using the -r option with read , but since you aren't, you could have the user escape their own spaces: 您可能应该将-r选项与read一起使用,但是由于您没有使用-r选项, 因此可以让用户转义其自己的空间:

$ read -a array    # foo bar hello\ world

You can pass your input to a function and make use of $@ to build your array: 您可以将输入传递给函数,并利用$@来构建数组:

makearr() { arr=( "$@" ); }

makearr foo bar hello world
# examine the array
declare -p arr
declare -a arr='([0]="foo" [1]="bar" [2]="hello" [3]="world")'

# unset the array
unset arr

makearr foo bar 'hello world'
# examine the array again
declare -p arr
declare -a arr='([0]="foo" [1]="bar" [2]="hello world")'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM