bash - for 循环遍历多个目录及其文件
我在同一路径 my_path/
中有 5 个目录:
my_path/1951
my_path/1952
my_path/1953
my_path/1954
my_path/1955
每个目录包含不同数量的以 .nc
结尾的 netcdf 文件。
我需要通过循环每个目录和文件来执行 CDO
命令。以下命令仅适用于第一个目录和文件my_path/1951/*.nc
:
for i in my_path/1951/*.nc
do
cdo selyear,1951/1970 "$i" "$i"2
done
该命令从目录中的 nc 文件中选择年份,从该目录的年份开始,到 20 年后结束。
因此,对于第二个目录,它将是:
for i in my_path/1952/*.nc
do
cdo selyear,1952/1971 "$i" "$i"2
done
对于第三个目录:
for i in my_path/1953/*.nc
do
cdo selyear,1953/1972 "$i" "$i"2
done
等等...
有没有一种方法可以使用唯一的 for 循环或嵌套 for 循环来完成所有操作,而不是为每个目录重复上面的 for 循环?
I have 5 directories in the same path my_path/
:
my_path/1951
my_path/1952
my_path/1953
my_path/1954
my_path/1955
Each directory contains a different number of netcdf files ending in .nc
.
And I need to perform a CDO
command by looping in each directory and files. The command below applies only to the first directory and files my_path/1951/*.nc
:
for i in my_path/1951/*.nc
do
cdo selyear,1951/1970 "$i" "$i"2
done
The command select years from the nc files in the directory starting from the year of the directory and ending 20 years later.
So for the second directory it will be:
for i in my_path/1952/*.nc
do
cdo selyear,1952/1971 "$i" "$i"2
done
and for the third:
for i in my_path/1953/*.nc
do
cdo selyear,1953/1972 "$i" "$i"2
done
etc...
Is there a way I can do everything with a unique for loop or nested for loop instead of repeating the for loop above for each directory?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
请您尝试以下操作:
它将命令行输出为空运行。如果看起来不错,请删除
echo
并运行。Would you please try the following:
It outputs command lines as a dry run. If it looks good, drop
echo
and run.您可以像这样循环:
shopt
命令确保即使某些目录不包含 nc 文件,循环也能正常工作。You could loop like this:
The
shopt
command ensures that the loop works even if some of the directories don't contain a nc file.您可以执行 On2 来获取 sh 脚本的参数。
之后,您可以将所有文件夹传递给您的脚本。
you can do On2 for with getting parameters of sh script.
After that you can pass all folder to your script.