Reputation: 99
I am using a batch file to convert data type of many climate files (*.nc). I used a for loop to iterate through the files. However, for some reason, it does not work properly.
Here is my code:
@echo off
for /l %%x in (2071,1,2100) do (
pause
C:\NCO\ncap2 -s prec=float(prec) Prec_Order_%%x.nc Prec_Order_F_%%x.nc
C:\NCO\ncap2 -s Tavg=float(Tavg) Tavg_Order_%%x.nc Tavg_Order_F_%%x.nc
C:\NCO\ncap2 -s Tmax=float(Tmax) Tmax_Order_%%x.nc Tmax_Order_F_%%x.nc
C:\NCO\ncap2 -s Tmin=float(Tmin) Tmin_Order_%%x.nc Tmin_Order_F_%%x.nc
C:\NCO\ncap2 -s Wspd=float(Wspd) Wspd_Order_%%x.nc Wspd_Order_F_%%x.nc
C:\NCO\ncap2 -s Srad=float(Srad) Srad_Order_%%x.nc Srad_Order_F_%%x.nc
C:\NCO\ncap2 -s Hspec=float(Hspec) Hspec_Order_%%x.nc Hspec_Order_F_%%x.nc
)
pause
The program does not work to the first pause. I've checked carefully, but cannot find out where the problem is in the line "for /l %%x in (2071,1,2100) do (".
Upvotes: 2
Views: 253
Reputation: 6707
From my point of view, the best way to write for
loops is to call a subroutine, as in the example below. This avoids all parenthesis problems.
for /L %%x in (2071,1,2100) do call :sp1 %%x
echo "done"
pause
goto :eof
:sp1
set arg=%1
echo arg = %arg%
C:\NCO\ncap2 -s prec=float(prec) Prec_Order_%arg%.nc Prec_Order_F_%arg%.nc
...
goto :eof
Upvotes: 1
Reputation: 34979
Most probably, the first closing parenthesis )
in the ncap2
command line is interpreted as the closing parenthesis of the entire for /L
loop, and so your code fails.
To overcome this, you need to escape all the closing )
in the loop body. Escaping in cmd
means to precede the characters by ^
. The opening (
do not need to be escaped but it does no harm either; I prefer to do it for cosmetical reasons mainly (so one can easily distinguish them from functional (
).
Here is the fixed code:
for /l %%x in (2071,1,2100) do (
pause
C:\NCO\ncap2 -s prec=float^(prec^) Prec_Order_%%x.nc Prec_Order_F_%%x.nc
C:\NCO\ncap2 -s Tavg=float^(Tavg^) Tavg_Order_%%x.nc Tavg_Order_F_%%x.nc
C:\NCO\ncap2 -s Tmax=float^(Tmax^) Tmax_Order_%%x.nc Tmax_Order_F_%%x.nc
C:\NCO\ncap2 -s Tmin=float^(Tmin^) Tmin_Order_%%x.nc Tmin_Order_F_%%x.nc
C:\NCO\ncap2 -s Wspd=float^(Wspd^) Wspd_Order_%%x.nc Wspd_Order_F_%%x.nc
C:\NCO\ncap2 -s Srad=float^(Srad^) Srad_Order_%%x.nc Srad_Order_F_%%x.nc
C:\NCO\ncap2 -s Hspec=float^(Hspec^) Hspec_Order_%%x.nc Hspec_Order_F_%%x.nc
)
pause
Upvotes: 1