2016-10-06 47 views
0

我浏览基于字符的输入分割问题,但不能完全弄清楚基于条件的多个字符:猛砸有条件字符串分割到数组

说我有这样的拆分输入分离的简单bash脚本用空格到一个数组:

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

我想一个额外的条件,其中,如果条款是由另一个字符封装,整个短语应该被分割为一体。

例如封装有一个反勾:

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

有一个在'FOO条\'世界你好\'' – anubhava

+0

@anubhava感谢澄清没有什么不同的分隔符。我没有得到任何关于bash的分隔符的具体定义,所以我尽我所知地认为它是用于分割输入的字符的同义词。我编辑了我的问题。 – Aaron

+1

Backtick用于BASH或POSIX中的命令替换。你可能会使用单引号,比如'foo bar'hello world'' – anubhava

回答

1

指定一个分隔符以外的空白呼叫到read

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

你或许应该使用的-r选项与read,但是既然你都没有,你可以用户逃避自己的空间:

$ read -a array # foo bar hello\ world 
0

可以传递您输入的功能,并利用[email protected]建立你的数组:

makearr() { arr=("[email protected]"); } 

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")'