Current Issue


Table of contents

CD-ROM

Sys Admin and The Perl Journal CD-ROM version 12.0

Version 12.0 delivers every issue of Sys Admin from 1992 through 2006 and every
issue of The Perl Journal from 1996-2002 in one convenient CD-ROM!

Order now!

Sys Admin Magazine > Archives > 2005 > June 2005

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.




MarketPlace

Free Download Speeds Up PCs
Make Your PC Faster --New Diskeeper 2008 Speeds Up PCs --Download Free Trial Now!

Six Sigma Certification
100% Online-Six Sigma Certificate from Villanova - Find Out More Now.

Automate Software Builds with Visual Build Pro
Easily create an automated, repeatable process for building and deploying software.

WinDev 12 - Powerful IDE
Develop 10 times faster ! ALM, IDE, .Net, RAD, 5GL, Database, 5GL, 64-bit, etc. Free Express version

Wanna see your ad here?