简体   繁体   English

Shell脚本多重生成器

[英]shell scripting Multiple generator

Hi :) Need help on a project, working on shell scripting and need to figure out how to print car names after certain numbers when they're divisible by certain numbers in a list. 嗨:)需要一个项目的帮助,需要编写Shell脚本,并且需要弄清楚如何在列表中将某些数字除以某些数字后再打印汽车名称。

Here's the generator, it takes two integers from the user, (Section where they're prompted not included), and prints the evens between those. 这是生成器,它从用户那里获取两个整数(不包括提示它们的部分),并在它们之间打印偶数。 I need to print car names after numbers divisible by: 5, 7, 10. 我需要在可被5、7、10整除的数字之后打印汽车名称。

5 = Ford 7 = Bmw 10 = Rover 5 =福特7 =宝马10 =罗孚

Generator: 发电机:

for ((n = n1; n<= n2; ++n)); do 
    out=$(( $n % 2 )) 
    if [ $out -eg 0 ] ; then 
        echo "$n" 
    fi
done 

Any help would be appreciated :( I'm completely clueless :( Thanks 任何帮助,将不胜感激:(我完全一无所知:(谢谢

Do you mean something like this? 你的意思是这样吗?

n1=0
n2=10

for ((n = n1; n <= n2; ++n)); do
    if (( n % 2 == 0)); then
        echo -n $n 
        if (( n %  5 == 0)); then
            echo -n ' Ford'
        fi
        if (( n %  7 == 0)); then
            echo -n ' BMW'
        fi
        if (( n % 10 == 0)); then
            echo -n ' Rover'
        fi
        echo
    fi
done

Output 输出量

0 Ford BMW Rover
2
4
6
8
10 Ford Rover

Not sure you want the 0 line containing names though, but that's how % works. 不确定您是否希望包含名称的0行,但这是%工作方式。 You can add an explicit check for 0 if you wish. 您可以根据需要添加0的显式检查。

awk to the rescue! awk解救!

$ awk -v start=0 -v end=70 -v pat='5=Ford,7=Bmw,10=Rover'
      'BEGIN{n=split(pat,p,","); 
             for(i=1;i<=n;i++)
               {split(p[i],d,"=");
                a[d[1]]=d[2]}
             for(i=start;i<=end;i+=2)
               {printf "%s ",i; 
                for(k in a) 
                   if(i%k==0) 
                      printf "%s ", a[k]; 
                print ""}}'

instead of hard coding the fizzbuzz values, let the program handle it for you. 而不是对Fizzbuzz值进行硬编码,让程序为您处理它。 script parses the pattern and assigns divisor/value to a map a . 脚本解析模式,并将除数/值分配给映射a While iterating over from start to end two by two check for each divisor and if divides append the tag to the line. 在从头到尾的迭代过程中,每两个因子进行两次检查,如果有除数,则将标记附加到行中。 Assumes start is entered as an even value if not need to guard for that too. 假设也不必为此而将启动输入为偶数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM