Adam Merckx
Adam Merckx

Reputation: 1244

Loops in Unix script

Currently, I have written my script in the following manner:

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

But I want the values in the form of some array like x=[10,9.7436,9.4872...,6.9231]

And I want the script to be called as follows:

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

Could someone please suggest a method to loop this?

Upvotes: 0

Views: 36

Answers (1)

Kurt Stutsman
Kurt Stutsman

Reputation: 4034

If you use bash, you can do arrays

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

Just make sure the elements in the array are separated by a space instead of comma and use parentheses instead of square bracket. The ${arr[@]} will expand as the elements of the array separated by a space. The ${x/./} will remove the decimal point from the element to make the filename suffix.

You could actually do it without an array at all by just putting the values separated by spaced in place of the ${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

or perhaps a little cleaner by using a normal variable

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

This works because expanding $values without surrounding quotes (ie "$values") will cause BASH to parse each word inside of the variable. So it's effectively the same as the previous code example.

Upvotes: 1

Related Questions