arrays - bash:具有两个数组参数的函数?如何调用以及如何解析?
问题描述
我想在 bash 中编写一个函数,它接受两个数组参数,如下所示:
#!/bin/bash
function RemoveElements
{
# $1 and $2 are supposed to be arrays
# This function should generate a new array, containing
# all elements from $1 that did not occur in $2
}
a=(1 3 5 7 8)
b=(2 3 6 7)
c=RemoveElements $a $b
# or perhaps: (if directly returning non-integer
# values from function is not possible)
c=$(RemoveElements $a $b)
# c should now be (1 5 8)
这可能吗?如果可以,正确的语法是什么?无论是在调用函数时,还是在函数内部处理数组?
解决方案
RemoveElements.sh 源代码:
#!/bin/bash
function RemoveElements {
for i in ${a[@]};do
MATCH=0
for j in ${b[@]};do
if [ $i -ne $j ];then
continue
else
MATCH=`expr $MATCH + 1`
fi
done
if [ $MATCH -eq 0 ];then
c=(${c[@]} $i)
fi
done
}
a=(1 3 5 7 8)
b=(2 3 6 7)
RemoveElements
echo "${c[@]}"
执行后:
# ./RemoveElements.sh
1 5 8
如您所见,所需的输出。
推荐阅读
- vba - 如何将整个范围从 Excel 粘贴到 Lotus 作为位图?
- python-3.x - 难以用 python 代码输入训练数据集
- python - 在 Python 中使用 MultiIndex 和 to_excel 时创建的标题下方的空行
- angular - 如何将完整 Angular 应用程序的工作源代码发布到 npm?
- angularjs - 为什么 $compile 在 ng-repeat 中创建多个元素?
- .net - 作为使用免费版 Visual Studio 的 Windows Installer 设置的一部分,如何更改 VB .net 应用程序的设置?
- asp.net-mvc - MVC:提交 Ajax.Beginform 后清除模型值
- python - 在最新版本的 python pandas 中创建 pandas.Series 在 Matlab 中不起作用
- sql - 根据单个单元格中的多个条件选择记录
- android - app:layout_constraint 值在 xml 源视图中始终显示为未定义 - Android Studio 3.2