Link to home
Start Free TrialLog in
Avatar of mistermuv
mistermuvFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Remove duplicate lines from a text file

Hi,

I am trying to remove duplicate lines from a text file. To make things difficult the lines contain non unique timestamps but a unique reference number. Some of the duplicates amount to 10 lines whereas others can only be 2 lines.

1. Here are some examples of duplicates lines: <timestamp>,<reference>,<error message>

08:47:22,95847170050,Problem inputting data.
08:47:29,95847170050,Problem inputting data.
08:47:35,95847170050,Problem inputting data.
08:53:28, 96672540040, More problems inputting data.
08:53:35, 96672540040, More problems inputting data.
08:53:41, 96672540040, More problems inputting data.

I want to delete all but the most recent duplicate line.

I am new to java so can you tell what the best way of doing this is?

Thank you in advance.
Avatar of RishadanPort
RishadanPort

Step 1. Read in All data to an Array of Strings
Step 2. Remove unwanted Lines.
Step 3. Insert back into file.

For Steps 1 and 3 you can use a FileStream with a read and write method
is a realitivly easy step

For step 2, you will need
1. Remove out the reference number by using the Substring method.
2. compare this reference number with other lines reference number
   2a If the reference number is the same remove one of the lines
   2b else skip
Here is sometimes very rough I did in a minutes...
		String[] fileLines = new String[1000];
		List<String> updatedLines = new List<String>();
 
		//populate the fileLines here
 
		String currentString;
		String referenceNumber;
 
		for (int index = 0; index < fileLines.length; index++)
		{
			currentString = fileLines[index];
 
			if(currentString == null)
			{
				continue;
			}
 
			referenceNumber = currentString.substring(referenceNumber.indexOf(","), referenceNumber.indexOf(",", referenceNumber.indexOf(","));
 
			referenceNumber = referenceNumber.trim();
 
			for (int index2 = index + 1; index2 < fileLines.length; index2++)
			{
				if(fileLines[index2].Contains(referenceNumber))
				{
					fileLines[index2] = null;
				}
			}
		}
 
		for(int index = 0; index < fileLines.length; index++)
		{
			if(fileLines[index] != null){
				updatedLines.add(fileLines[index]);
			}
		}

Open in new window

SOLUTION
Avatar of RishadanPort
RishadanPort

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of mistermuv

ASKER

RishadanPort.

As I am new to java can you tell where in the code it differentiates the duplicate lines by timestamp so that only the most recent duplicate line remains whereas all the others are deleted?

Thankyou
Ah, I didn't know you wanted to keep the most recent TimeStamp as well... That's another issue altogether.

Now you will need to do this.

1. Find all Strings that contain the reference numbers
2. for each of these strings that contain the reference numbers you will need to also parse out timestamp, and string compare them.  
for comparing the TimeStamps, you can use a simple string compare operation:

Example:
String timestamp1 = "08:47:22";
String timestamp2 = "08:57:41";
int compareInt = String.Compare(timestamp1, timestamp2);

if(compareInt < 0){
   //timestamp1 is earlier then timestamp2
}
else{
///timepstamp2 is ealier then timestamp1
}

Note this way only works if the format of the timestamps stay the same in that order...

For example if in your code it does something like this:
timestamp1 = 0:00:10
then something like this
timestamp2 = 01:00:00
then this way is not a good way to do it... and you will have to use some DateTime Class to handle it for you.
Avatar of CEHJ
You can use a Set to remove duplicates, together with a Wrapper class for the file line:
import java.io.*;
import java.util.*;
 
public class Uniq {
	public static void main(String[] args) {
		if (args.length < 2) {
		    System.err.println("Usage: java Uniq <infile> <outfile>");
		    System.exit(1);
		}
		Uniq u = new Uniq();
		Set<Line> lines = u.read(args[0]);
		u.write(lines, args[1]);
	}
 
	public Set<Line> read(String fileName) {
		Set<Line> lines = new LinkedHashSet<Line>();
		Scanner s = null;
		try {
			s = new Scanner(new File(fileName));
			while (s.hasNextLine()) {
				lines.add(new Line(s.nextLine()));
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			s.close();
		}
		return lines;
	}
 
	public void write(Set<Line> lines, String fileName) {
		PrintWriter out = null;
		try {
			out = new PrintWriter(new FileWriter(fileName));
			for (Line line : lines) {
				out.println(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			out.close();
		}
	}
}
 
 
class Line {
	private String line;
	private String[] atoms;
 
	public Line(String line) {
		this.line = line;
		atoms = line.split("\\s*,\\s*");
	}
 
	public String getLine() {
		return this.line;
	}
 
	public void setLine(String line) {
		this.line = line;
	}
 
	public boolean equals(Object o) {
		Line otherLine = (Line) o;
		return atoms[1].equals(otherLine.atoms[1]);
	}
 
	public int hashCode() {
		return atoms[1].hashCode();
	}
 
	public String toString() {
	    return line;
	}
}

Open in new window

Hi CEHJ,

When I compile your code I get the following:  I can't see anything wrong with it.
I am compiling against j2sdk1.4.2_17 due to work contraints.

>javac Uniq.java
Uniq.java:15: <identifier> expected
      public Set<Line> read(String fileName) {
                  ^
Uniq.java:44: ';' expected
}
^
2 errors
Yes, my code uses generics, which is >= Java 1.5. Remove everything in angle brackets and cast appropriately
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I think the "scanner" class was introduced in v1.5 too.

>javac Uniq.java
Uniq.java:17: cannot resolve symbol
symbol  : class Scanner
location: class Uniq
      Scanner s = null;
                ^
Uniq.java:19: cannot resolve symbol
symbol  : class Scanner
location: class Uniq
      s = new Scanner(new File(fileName));
                                ^
2 errors
I suppose I would have to use the traditional methods of utilising FileReader and BufferedReader and the such like.
>>I think the "scanner" class was introduced in v1.5 too.

Sorry, yes. BufferedReader can be used instead. Running the app i posted produces:

08:47:22,95847170050,Problem inputting data.
08:53:28, 96672540040, More problems inputting data.
:-)