Eight Ways to Reverse a File
Ed Schaefer and John Spurgeon
In this article, we present eight ways to reverse a file. Suppose the data
file contains the following:
1. There
2. is
3. more
4. than
5. one
6. way
7. to
8. skin
9. a
10. cat
We just want to reverse it to:
10. cat
9. a
8. skin
7. to
6.way
5. one
4. than
3. more
2. is
1. There
This is a simple problem, so why do we present eight methods for solving it?
Since this is essentially a file-access problem, we're hoping to make you think
about which tool to use the next time you process a large file. We're also testing
the methods to determine which are the most efficient. See the sidebar
for a comparison.
Table 1.
Here are the methods we tested:
- Using vi
- Using an array (using both awk and the shell)
- Using Perl's print reverse command
- Using the tail command's reverse (-r) option
- Using GNU's tac
- Using sed
- Using a dynamic numeric field
- Using shell variables
Using vi
One obscure method is using vi's move attribute. From within vi, using
the command mode, execute:
:g/^/move0
Identify each line, /^/, and move it below line 0. Since line 0 does not
exist, each line in the file is placed at the top of the file pushing each succeeding
line down.
The vi editor recognizes the move pattern using the first letter abbreviation,
so the command can be shortened to:
:g/^/m0
Consider another example, where the file isn't to be reversed until after line
2:
1.
|