Unix脚本中的循环

时间:2016-03-22 13:25:38

标签: loops unix

目前,我已按以下方式编写了我的脚本:

c3d COVMap.nii -thresh 10 Inf 1 0 -o thresh_cov_beyens_plus10.nii
c3d COVMap.nii -thresh 9.7436 Inf 1 0 -o thresh_cov_beyens_plus97436.nii
c3d COVMap.nii -thresh 9.4872 Inf 1 0 -o thresh_cov_beyens_plus94872.nii
c3d COVMap.nii -thresh 9.2308 Inf 1 0 -o thresh_cov_beyens_plus92308.nii
c3d COVMap.nii -thresh 8.9744 Inf 1 0 -o thresh_cov_beyens_plus89744.nii
c3d COVMap.nii -thresh 8.7179 Inf 1 0 -o thresh_cov_beyens_plus87179.nii
c3d COVMap.nii -thresh 8.4615 Inf 1 0 -o thresh_cov_beyens_plus84615.nii
c3d COVMap.nii -thresh 8.2051 Inf 1 0 -o thresh_cov_beyens_plus82051.nii
c3d COVMap.nii -thresh 7.9487 Inf 1 0 -o thresh_cov_beyens_plus79487.nii
c3d COVMap.nii -thresh 7.6923 Inf 1 0 -o thresh_cov_beyens_plus76923.nii
c3d COVMap.nii -thresh 7.4359 Inf 1 0 -o thresh_cov_beyens_plus74359.nii
c3d COVMap.nii -thresh 7.1795 Inf 1 0 -o thresh_cov_beyens_plus71795.nii
c3d COVMap.nii -thresh 6.9231 Inf 1 0 -o thresh_cov_beyens_plus69231.nii

但是我想要像x=[10,9.7436,9.4872...,6.9231]

这样的数组形式的值

我希望脚本调用如下:

x=[10,9.7436,9.4872...,6.9231]
c3d COVMap.nii -thresh x[0] Inf 1 0 -o thresh_cov_beyens_plus10.nii
c3d COVMap.nii -thresh x[1] Inf 1 0 -o thresh_cov_beyens_plus97436.nii
c3d COVMap.nii -thresh x[2] Inf 1 0 -o thresh_cov_beyens_plus94872.nii
c3d COVMap.nii -thresh x[3] Inf 1 0 -o thresh_cov_beyens_plus92308.nii
...
c3d COVMap.nii -thresh x[14] Inf 1 0 -o thresh_cov_beyens_plus87179.nii

有人可以建议一个方法来循环吗?

1 个答案:

答案 0 :(得分:1)

如果你使用bash,你可以做数组

arr=(10 9.7436 9.4872 ... 6.9231)

for x in ${arr[@]}; do
    c3d COVMap.nii -thresh $x Inf 1 0 -o thresh_cov_beyens_plus${x/./}.nii
done

确保数组中的元素用空格而不是逗号分隔,并使用括号而不是方括号。 ${arr[@]}将扩展为由空格分隔的数组元素。 ${x/./}将从元素中删除小数点以使文件名后缀。

实际上你可以在没有数组的情况下完成它,只需将值间隔开来代替${arr[#]}

for x in 10 9.7436 9.4872 ... 6.9231; do
    c3d COVMap.nii -thresh $x Inf 1 0 -o thresh_cov_beyens_plus${x/./}.nii
done

或者使用普通变量

可能更清洁一点
values="10 9.7436 9.4872 ... 6.9231"

for x in $values; do
    c3d COVMap.nii -thresh $x Inf 1 0 -o thresh_cov_beyens_plus${x/./}.nii
done

这是有效的,因为展开$values而不包含引号(即"$values")将导致BASH解析变量内的每个单词。所以它与前面的代码示例实际上是一样的。