Wednesday, May 27, 2009

Need to prefix lines of a text file or add a new first column to a log file?

This easy but handy script will add a new column to your file. In this example the column will contain the text 'someserver-(n)' the (n) will be numbers starting from 1 to the number of lines in the file. See the output at the bottom. This is useful if you ever have to combine like files, log files are a good example.

Put this text in a file called addcolumn.pl.

#!/bin/perl

my $prefixtext = "someserver";

while ($x=<>) {
$y++;
print "$prefixtext-$y $x";
}

Now make the perl script executable like this:

> chmod +x addcolumn.pl

Now you can do something like this. Let's say you have a log file called access.log (could be an apache log file for example).

> cat access.log | addcolumn.pl > newaccess.log

the output of this script looks like this:

someserver-1 rest of line...
someserver-2 rest of line...
someserver-3 rest of line...

and will be captured in a new file called newaccess.log

No comments: