如何将csh数组元素与空格以外的东西分开?

时间:2015-04-19 00:36:42

标签: arrays csh separator

在我正在编写的csh脚本中,我需要包含空格的数组元素,所以我需要将这些元素与空格之外的东西分开,比如逗号。例如,我想用以下内容初始化我的数组:

set the_array=('Element 1','Element 2','Element 3','Element 4')

注意:我很清楚在csh中工作有多么不受欢迎。然而,对于这个项目,我别无选择......是的,我试图说服权力应该改变,但是已经有一个庞大的代码库需要重新编写,这样就被拒绝了。

1 个答案:

答案 0 :(得分:5)

在CSH中有两种初始化字符串数组(其中包含空格)的方法:

第一种方法是使用逗号语法或“glob pattern”:

% set the_array = {'Element 1','Element 2','Element 3','Element 4'}
% echo $the_array[1]
Element 1

第二种方式,没有逗号,使用括号:

% set the_array = ('Element 1' 'Element 2' 'Element 3' 'Element 4')
% echo $the_array[1]
Element 1

这种方式还允许您在多行上创建数组:

% set the_array = ('Element 1' \
? 'Element 2')
% echo $the_array[1]
Element 1
% echo $the_array[2]
Element 2

要遍历the_array,您无法简单地访问foreach中的每个元素,如下所示:

% foreach i ( $the_array )
foreach? echo $i
foreach? end
Element
1
Element
2
Element
3
Element
4

你需要使用seq从1循环到N,其中N是数组的长度,如下所示:

% foreach i ( `seq $the_array` )
foreach? echo $the_array[$i]
foreach? end
Element 1
Element 2
Element 3
Element 4

请注意,CSH使用基于1的索引。

不幸的是,正如您所发现的那样,使用带逗号的括号将产生以下内容:

% set the_array = ('Element 1','Element 2','Element 3','Element 4')
% echo $the_array[1]
Element 1,Element 2,Element 3,Element 4

来源