-2

我有两个输入文件,一个只包含数字,例如

范围.txt

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11    
12  
13  
14  
15  
16  
17  
18  

另一个文件有要求。例如

要求.txt

2s 4m  
1s 10m  

这意味着 2 组每组 4 名成员和 1 组 10 名成员。

输出应如下所示:

There is 1 apple;  
There are 2 mangoes and 1 apple;   
There are 3 mangoes and 1 apple;   
There are 4 mangoes and 1 apple;  
There is 5 apple;  
There are 6 mangoes and 5 apple;  
There are 7 mangoes and 5 apple;  
There are 8 mangoes and 5 apple;  
There is 9 apple;  
There are 10 mangoes and 9 apple;  
There are 11 mangoes and 9 apple;  
There are 12 mangoes and 9 apple;  
There are 13 mangoes and 9 apple;  
There are 14 mangoes and 9 apple;  
There are 15 mangoes and 9 apple;  
There are 16 mangoes and 9 apple;  
There are 17 mangoes and 9 apple;  
There are 18 mangoes and 9 apple;     

如何使用 awk 和 shell 脚本(甚至 perl)来实现这一点?我们拥有的 awk 版本是 /usr/xpg4/bin/awk。我不熟悉数组,这就是为什么需要一些帮助。
谢谢 !

PS:刚刚更新了将苹果“价值”附加到芒果“价值”的要求。

4

2 回答 2

3
awk '
    {
        sets = 0+$1
        mbrs = 0+$2
        for (i=1; i<=sets; i++)
            groups[idx++] = mbrs
    }

    END {
        for (idx in groups) {
            getline < range
            printf "There is %d apple;\n", $1
            for (i=2; i<=groups[idx]; i++) {
                getline < range
                printf "There are %d mangoes;\n", $1
            }
        }
    }
' range=range.txt requirements.txt

或者

perl -Mautodie -nE '
    BEGIN { open $range, "<", shift }
    next unless /(\d+)s (\d+)m/;
    ($sets, $mbrs) = ($1, $2);
    for $i (1..$sets) {
        chomp( $n = <$range> );
        say "There is $n apple;";
        for $j (2..$mbrs) {
            chomp( $n = <$range> );
            say "There are $n mangoes;";
        }
    }
' range.txt requirements.txt
于 2013-07-19T18:31:22.810 回答
1

awk

awk -F "[sm]" '{ for (set=1; set<=$1; set++) {
                   getline ct < "range.txt"
                   print "There is " ct " apple;"
                   for (member=1; member<=$2; member++) {
                     getline ct < "range.txt"
                     print "There are " ct " mangoes;"
                   }
                 }
               }' requirements.txt

requirements.txt这使用sandm字符作为分隔符进行解析。当它遍历这两个数字时,它将每一行range.txt用作ct要显示在输出中的变量。

于 2013-07-19T18:42:51.880 回答