Thursday, August 14, 2008

Execute a perl script from java Program

Interested to execute a perl script from a java program.... uhmmmmm... see below java program (Sample.java)

import java.io.*;

public class Sample{

public static void main(String args[]) {

Process process;

try
{
process = Runtime.getRuntime().exec("perl testscript.pl");
process.waitFor();
if(process.exitValue() == 0)
{
System.out.println("Command Successful");
}
else
{
System.out.println("Command Failure");
}
}
catch(Exception e)
{
System.out.println("Exception: "+ e.toString());
}
}
}

javac Sample.java
java -cp . Sample

compare two sorted files in unix

If you wanted to compare 2 sorted files then use comm command. comm command compares two sorted files line by line. This command reads the File1 and File2 as parameter and writes a three column output to standard output.

First Column: Lines that are only in File1
Second Column: Lines that are only in File2
Third Column: Lines that are in both File1 and File2

Syntax:

comm [-1] [-2] [-3 ] file1 file2

-1 Suppresses the display of the first column (lines in File1)
-2 Suppresses the display of the second column (lines in File2)
-3 Suppresses the display of the third column (lines both in File1 and File2)

Killing a defunct process

A defunct (or "zombie") process is a process that isn't running, isn't eligible to run, and takes up no system resources. It's actually a process that has exited, but its parent has not called wait() in order to find out its exit status.

defunct processes can't be killed since they are already dead. To make them disappear you have to kill their parent process.

Find the parent process id of the defunct process and then kill that parent process:

ps -fe | grep defunctprocess | awk '{print $3}'

kill -9 parentprocessid

Reverse the contents of a file

If you wanted to reverse the contents of a file, use below perl script:


#!/usr/bin/perl

$filename = "a.java";
open(INFILE, "<", $filename)
or die "Can't open $filename for reading: $!\n";
my(@content) = <INFILE>;
close(INFILE);
while (@content) {
my($line) = pop(@content);
chomp $line;
print reverse($line)."\n";
}

Reversing a file

You have a file and you wanted to reverse it. How to do it? Guys...... its really very easy.. Use below commands:


tail -r filename
or
cat -n filename | sort -nr | cut -c8-

You can achieve the same by writing a perl script. See below perl script:


#!/usr/bin/perl

$filename = "a.java";
open(INFILE, "<", $filename)
or die "Can't open $filename for reading: $!\n";
my(@content) = <INFILE>;
close(INFILE);
while (@content) {
my($line) = pop(@content);
chomp $line;
print "$line \n";
}