我有两个输入文件,其中一个只包含数字,例如
range.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。我不熟悉阵列,这就是为什么需要一些帮助
谢谢
附言:刚刚更新了在芒果"值"后面加上苹果"值"的要求。
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
使用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
这将使用s
和m
字符作为分隔符来解析requirements.txt
。当它在两个数字上循环时,它使用range.txt
中的每一行作为要在输出中显示的ct
变量。