Basic Example of an Array OF AWK 【每日一译】--2013-01-27

本文介绍了一个简单程序,该程序处理多行文本,每行以行号开头,并按行号顺序输出。程序通过创建一个数组来存储和排序行号,从而实现按行号排序输出文本的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The following program takes a list of lines, each beginning with a line number, and prints them
out in order of line number. The line numbers are not in order, however, when they are first read:
they are scrambled. This program sorts the lines by making an array using the line numbers as
subscripts. It then prints out the lines in sorted order of their numbers. It is a very simple program,

and gets confused if it encounters repeated numbers, gaps, or lines that don't begin with a number.

以下的程序处理了一个多行列,每行以一个行号开头,并且通过行号的顺序打印出他们。行号没有

按顺序排序,当它们第一次被读取时:它们进行比对。这个程序排序行号通过使用一个数组中使用行号作

为子脚本处理。然后它以它们的数字排序顺序输出所有的行。这是一个非常简单的程序,它将出现

混乱当它冲到重复的数字,漏洞,或者是行没有以数字开头。


{
if ($1 > max)
max = $1
arr[$1] = $0
}
END {
for (x = 1; x <= max; x++)
print arr[x]
}

The first rule keeps track of the largest line number seen so far; it also stores each line into the
array arr, at an index that is the line's number.
The second rule runs after all the input has been read, to print out all the lines.

When this program is run with the following input:

第一次规则保留跟踪最大的行号,迄今为止为睛可以看到的,它也将整行存储到数组ARR,并以行

号作为其索引。

第二次规则是在所有的输入被读取的后,再打印出所有的行。

5 I am the Five man
2 Who are you? The new number two!
4 . . . And four on the floor
1 Who is number one?

3 I three you.


its output is this:


1 Who is number one?
2 Who are you? The new number two!
3 I three you.
4 . . . And four on the floor
5 I am the Five man
If a line number is repeated, the last line with a given number overrides the others.
Gaps in the line numbers can be handled with an easy improvement to the program's END rule:
END {
for (x = 1; x <= max; x++)
if (x in arr)
print arr[x]
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值