具有基于参数范围的For循环 [英] For loop with an argument based range

查看:58
本文介绍了具有基于参数范围的For循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对一组按字典顺序命名的文件(10之前为01-09)运行某些操作.我必须使用一个相当旧的FreeBSD版本(7.3),所以不能使用echo {01..30}seq -w 1 30之类的幽默感.

I want to run certain actions on a group of lexicographically named files (01-09 before 10). I have to use a rather old version of FreeBSD (7.3), so I can't use yummies like echo {01..30} or seq -w 1 30.

我找到的唯一可行的解​​决方案是printf "%02d " {1..30}.但是,我无法弄清楚为什么我不能使用$1$2而不是130.当我运行脚本(bash ~/myscript.sh 1 30)时printf说{1..30}: invalid number

The only working solution I found is printf "%02d " {1..30}. However, I can't figure out why can't I use $1 and $2 instead of 1 and 30. When I run my script (bash ~/myscript.sh 1 30) printf says {1..30}: invalid number

AFAIK,bash中的变量是无类型的,所以printf如何不能接受整数参数作为整数?

AFAIK, variables in bash are typeless, so how can't printf accept an integer argument as an integer?

推荐答案

好,我终于明白了!

#!/bin/bash
#BSD-only iteration method    
#for day in `jot $1 $2`
for ((day=$1; day<$2; day++))
do
    echo $(printf %02d $day)
done

最初,我想将循环迭代器用作文件名中的一天",但现在我看到,在我的确切情况下,遍历普通数字(1、2、3等)并将它们处理为词典顺序会更容易循环内的那些.使用jot时,请记住$1是数字数量,而$2是起点.

I initially wanted to use the cycle iterator as a "day" in file names, but now I see that in my exact case it's easier to iterate through normal numbers (1,2,3 etc.) and process them into lexicographical ones inside the loop. While using jot, remember that $1 is the numbers amount, and the $2 is the starting point.

这篇关于具有基于参数范围的For循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆