Created
October 21, 2011 11:01
-
-
Save MagnusEnger/1303572 to your computer and use it in GitHub Desktop.
Read through a file and pick out lines that contain one of a number of "trigger" strings. Print the lines grouped by the string they matched, then print the remaining lines.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl -w | |
# Read through a file and pick out lines that contain one of a number of | |
# "trigger" strings. Print the lines grouped by the string they matched, then | |
# print the remaining lines. | |
# | |
# Usage: linesort.pl myfile.txt | |
use File::Slurp; | |
use Array::Each qw( rewind ); | |
use strict; | |
# These are the trigger strings we are looking for | |
my @triggers = ('foo', 'bar', 'baz'); | |
# Read in the lines from the file given on the command line | |
my @lines = read_file( $ARGV[0] ); | |
# An array for temporarily holding lines that did not contain a match | |
my @tmp; | |
foreach my $trigger ( @triggers ) { | |
print "\n*** $trigger\n"; | |
while ( my $line = shift @lines ) { | |
if ($line =~ m/$trigger/) { | |
print $line; | |
} else { | |
# Assign the lines that did not contain a match to a temporary array so | |
# we don't forget them, but can try them with another trigger word | |
push @tmp, $line; | |
} | |
} | |
# Assign the lines that did not contain a hit this time to the original array | |
# so we can have another go at it | |
@lines = @tmp; | |
# Make sure the temporary array is empty | |
@tmp = (); | |
} | |
# Print out the remaining lines | |
print "\n\n*** The rest\n", @lines; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment