Solved

How to get the list of line numbers with the diff command in Perl?

Posted on 2013-05-29
1
345 Views
Last Modified: 2013-06-03
Hi,
I need to figure out which lines are different in two files. And I need the exact line numbers that are different then I want to put them in an array.

The sudo code will be like this:

do diff on two files (new file and old file).

get the line numbers that were edited (added or deleted) in the new file.

put the line numbers in an array

Open in new window


How can do it in Perl?

Thanks,
0
Comment
Question by:Tolgar
1 Comment
 
LVL 23

Accepted Solution

by:
nemws1 earned 500 total points
ID: 39206024
This is what I whipped up:

#!/usr/bin/perl
my $f1start, $f2start, $junk;
open(DIFF, "diff test1 test2 |");
while (<DIFF>) {
    chomp;
    if (/^\d/) {            # line numbers
        ($f1start, $f2start) = split('c', $_);
        if ($f1start =~ /,/) {
            ($f1start, $junk) = split(',', $f1start);
        }
        if ($f2start =~ /,/) {
            ($f2start, $junk) = split(',', $f2start);
        }
        next;
    }
    if (/^\<\s/) {          # only in first file
        print $f1start++;
        print " $_\n";
    }
    if (/^-+/) {
        next;
    }
    if (/^\>\s/) {          # only in second file
        print $f2start++;
        print " $_\n";
    }
}

close(DIFF);

Open in new window

0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

I've just discovered very important differences between Windows an Unix formats in Perl,at least 5.xx.. MOST IMPORTANT: Use Unix file format while saving Your script. otherwise it will have ^M s or smth likely weird in the EOL, Then DO NOT use m…
In the distant past (last year) I hacked together a little toy that would allow a couple of Manager types to query, preview, and extract data from a number of MongoDB instances, to their tool of choice: Excel (http://dilbert.com/strips/comic/2007-08…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…

730 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question