Sunday, December 28, 2008

Perl : Get filename or directory name from an absolute path

Use Perl's File module to get Filename or directory name from an absolute path. Below is an example of how to do this:

#!/usr/bin/perl
use File::Basename;

print getDirPath("/mnt/users/vishnu/blog/PerlPost.html");
print getFileNameWithoutExt("/mnt/users/vishnu/blog/PerlPost.html");
print getFileName("/mnt/users/vishnu/blog/PerlPost.html");

sub getDirPath() {
return dirname($_[0]);
}

sub getFileNameWithoutExt() {
my $file = basename($_[0]);
$file =~ s/\.[^.]*$//;
return $file;
}

sub getFileName() {
return basename($_[0]);
}


Output of above program would be:
/mnt/users/vishnu/blog
PerlPost
PerlPost.html

Saturday, December 20, 2008

Perl error: Can't locate module in @INC

If you get a Perl error message like Can't locate module.pm in @INC, this message means that the Perl module you're trying to include (like the module named module) can't be found in Perl's include path, which is represented by the variable named @INC.

Perl uses an @INC variable that contains the directories it will search in when you specify that you want to include a module, but you can't look at it like an environment variable. Although Perl doesn't have something like the CLASSPATH environment variable you can easily look at, you can print the @INC variable with a simple one-line command. The following Perl command shows the directories that Perl looks in when it tries to load modules:

perl -e 'print join("\n", @INC);'

Including a perl module your @INC include path

There are different ways by which you can add your perl module in @INC include path
1. Specify it in PERL5LIB environment variable
export PERL5LIB=path

2. Perl takes -I option where you can specify the additional directories where it should search for modules.
perl -I path myscript.pl

3. Modify your Perl program to find the module by adding below line near the top of Perl programs. This simple line of code tells your Perl program to add this directory to it's @INC search directory.
use lib "path"

Friday, December 19, 2008

Perl: FileDiff utility

I have 2 csv files (pipe seperated), one column (basically an Id field) is common in both the files. I need to compare both the files on the basis of this common field and print the lines which has common Id, Lines with id which is only in file1 and vice-versa. I thought up for writing perl script for this task. See below script.

Thursday, November 6, 2008

Oracle: Binary operations

Today i faced a situation when i need to do binary operations in Oracle Query. I had no idea how to do it. Obviously Googling worked as always. :-) :-) . Below was the problem:

I need to apply AND operation on a hexadecimal number as below but following query did not work.

select <num> & 0xf from dual;

I found that BITAND function will do this task, so i chnaged above query to as below and it worked.

select BITAND(<num>, 15)+0 from dual;
(here 15 is equivalent to 0xf, Note that BITAND returns a binary integer, so to use it in SQL you will need to convert it to a numeric.)

Similarly, Oracle has BITOR function for OR operation.

AARTI: Shree Google Maharaaj :-)

Recently i got an email from one of my friends which had Aarti for Google. Though it is in Hindi but i thought it to share with you all. If you know Hindi, then just read it and enjoy .. :) :)

Wednesday, October 22, 2008

Group rows of a csv file with sum of column values

You have heard about Group functionality in Microsoft Excel, which group the rows on a common value and does the sum of other field. Same thing can be done in unix using awk very easily. See below example:

[ ~]# cat test.csv
a,5
b,10
a,4
c,8
b,9
b,4
[ ~]# awk -F"," '{sum[$1] += $2 } END { for(n in sum)print n"=" sum[n] }' test.csv
a=9
b=23
c=8

Perl version of above script can be seen here:

Thursday, October 16, 2008

AWK examples

Find number of columns in a pipe seperated csv file
awk -F"|" '{print NF}' vishnu.csv |uniq

Find sum of column of a pipe seperated csv file
awk -F"|" '{sum += $col } END { print sum }' vishnu.csv
awk -F"|" '{sum += $col } END { print sprintf("%.2f",sum) }' vishnu.csv (print float value)

Replace tab character with a pipe symbol in a csv file
awk '{gsub("\t","|");print}' vishnu.csv

print the 5th and 7th columns of csv file if 5th and 7th column values are not same
awk -F"," '{if($5 != $7) {print $5","$7}}' test.csv

print the line of csv file if 5th and 7th column values are same
awk -F"," '{if($5 !== $7) {print}}' test.csv

Tuesday, October 14, 2008

Puzzle: Elevator problem

Question: A man lives on the twelfth floor of an apartment building. Every morning he takes the elevator down to the lobby and leaves the building. In the evening, he gets into the elevator, and, if there is someone else in the elevator -- or if it was raining that day -- he goes back to his floor directly. Otherwise, he goes to the tenth floor and walks up two flights of stairs to his apartment.

Answer: The man is a dwarf. He can't reach the upper elevator buttons, but he can ask people to push them for him. He can also push them with his umbrella.

Puzzle: 100 doors in a row

You have 100 doors in a row that are all initially closed. you make 100 passes by the doors starting with the first door every time. the first time through you visit every door and toggle the door (if the door is closed, you open it, if its open, you close it). the second time you only visit every 2nd door (door #2, #4, #6). the third time, every 3rd door (door #3, #6, #9), etc, until you only visit the 100th door.

for example, after the first pass every door is open. on the second pass you only visit the even doors (2,4,6,8...) so now the even doors are closed and the odd ones are opened. the third time through you will close door 3 (opened from the first pass), open door 6 (closed from the second pass), etc..

question: what state are the doors in after the last pass? which are open which are closed?





Solution: you can figure out that for any given door, say door #42, you will visit it for every divisor it has. so 42 has 1 & 42, 2 & 21, 3 & 14, 6 & 7. so on pass 1 i will open the door, pass 2 i will close it, pass 3 open, pass 6 close, pass 7 open, pass 14 close, pass 21 open, pass 42 close. for every pair of divisors the door will just end up back in its initial state. so you might think that every door will end up closed? well what about door #9. 9 has the divisors 1 & 9, 3 & 3. but 3 is repeated because 9 is a perfect square, so you will only visit door #9, on pass 1, 3, and 9... leaving it open at the end. only perfect square doors will be open at the end.


Puzzle: get exactly 2 liters with the 4 ltr and 7 ltr jars

The Problem:

You've got two jars, one of them fits exactly 7 liters, the other one fits exactly 4 liters. How could you get exactly 2 liters with these two jars? You have unlimited supply of water and you are allowed to spoil some water.


The Solution:

7 0 fill the 7 ltr jar completely
3 4 fill the 4 ltr jar using the 7 ltr one completely
3 0 empty the 4 ltr jar
0 3 fill all water from 7 ltr jar to 4 ltr water
7 3 fill the 7 ltr jar completely
6 4 fill 4 ltr jar from 7 ltr one completely
6 0 empty the 4 ltr jar
2 4 fill 4 ltr jar from 7 ltr one completely
2 0 empty the 4 ltr jar

Now you have exactly 2 ltrs in 7 ltr jar

Monday, October 13, 2008

Solaris: colorize stuff

If you want to colorize directory listing in solaris, just add the following alias in your .bashrc

alias ls='ls -h --color=auto'

If you want to colorize vim editor, add below in your .bashrc

export TERM=dtterm (for solaris)
export TERM=xterm (for linux)



Perl: Date formatting

If you need to convert Date from YYYY-MM-DD format to MM/DD/YYYY format, use below perl code.

$str="2008-10-13";
$str =~s/^(\d{4})\-(\d{2})\-(\d{2})/$2\/$3\/$1/;
print $str;

will output:
10/13/2008

sed examples

Delete a line from file which contain particular string (sed -e "//d" file1 > newfile)
print all lines except first line (sed -n '2,$p' vishnu.csv)
Convert YYYYMMDD to MM/DD/YYYY (echo "YYYYMMDD"|sed -n -e "s_\(....\)\(..\)\(..\)_\2/\3/\1_p")
Remove tab character from a file (sed -e \"s/[ <TAB>]*//g\" file > output)
Find and replace values in a file (sed -i 's/find1/replace1/g' fileName)
View only lines of a file that contains a particular string (sed -n '/string/p' fileName)
View particular row number (let say 3rd) of file (sed -n '3p;3q' fileName)
View range of row (let say 2 to 8) of file (sed -n '2,8p;8q' fileName)


Friday, October 10, 2008

Perl : Formatting a number to currency format

sub formatCurrency {
my $number = sprintf "%.2f", shift @_;
# Add one comma each time through the do-nothing loop
1 while $number =~ s/^(-?\d+)(\d\d\d)/$1,$2/;
# Put the dollar sign in the right place
$number =~ s/^(-?)/$1\$/;
return $number;
}


Saturday, September 20, 2008

How to access secure website (https) in HTTPUNIT

If you are using httpunit to automate your website testing and your site is on secure domain (i.e. on https); httpunit would not be able to access your site unless you add below code in your tests(probably in setup() method)

//code to make test case run for HTTPS site com.sun.net.ssl.internal.www.protocol.https.HttpsURLConnectionOldImpl.setDefaultHostnameVerifier(new com.sun.net.ssl.HostnameVerifier()
{
public boolean verify(String urlHostname, String certHostname)
{
return true;
}
}
);

Friday, September 19, 2008

Change the case of file contents

If you want to change case (either lower or upper case) of contents of a file use the tr command.

Change contents of filename to lower case
cat filename | tr "[:upper:]" "[:lower:]" > newfilename
or
cat filename | tr '[A-Z]' '[a-z]' > newfilename

Change contents of filename to upper case
cat filename | tr "[:lower:]" "[:upper:]" > newfilename
or
cat filename | tr '[a-z]' '[A-Z]' > newfilename

Tuesday, September 9, 2008

Determining the disk space used by Oracle schema

Run below query to find out how much disk space is being used by an Oracle schema

Select SUM(bytes)/1024/1024/1024 Gb, tablespace_name FROM user_segments GROUP BY tablespace_name;

Sunday, September 7, 2008

Memory usage by process

Solaris pmap command provides the memory usage of a process. This command tells you how much of memory a particular process is using and how much of there particular threads/heap are using. It's a very useful command to debug cases where you have to find that who is consuming more memory in your process.

pmap <PID>

example$ pmap 102905
102905: sh
00010000 192K r-x-- /usr/bin/ksh
00040000 8K rwx-- /usr/bin/ksh
00042000 40K rwx-- [ heap ]
FF180000 664K r-x-- /usr/lib/libc.so.1
FF236000 24K rwx-- /usr/lib/libc.so.1
FF23C000 8K rwx-- /usr/lib/libc.so.1
FF250000 8K rwx-- [ anon ]
FF260000 16K r-x-- /usr/lib/en_US.ISO8859-1.so.2
FF272000 16K rwx-- /usr/lib/en_US.ISO8859-1.so.2
FF280000 560K r-x-- /usr/lib/libnsl.so.1
FF31C000 32K rwx-- /usr/lib/libnsl.so.1
FF324000 32K rwx-- /usr/lib/libnsl.so.1
FF340000 16K r-x-- /usr/lib/libc_psr.so.1
FF350000 16K r-x-- /usr/lib/libmp.so.2
FF364000 8K rwx-- /usr/lib/libmp.so.2
FF380000 40K r-x-- /usr/lib/libsocket.so.1
FF39A000 8K rwx-- /usr/lib/libsocket.so.1
FF3A0000 8K r-x-- /usr/lib/libdl.so.1
FF3B0000 8K rwx-- [ anon ]
FF3C0000 152K r-x-- /usr/lib/ld.so.1


Sorting a csv file on a particular field

I have below csv file, which have around 5k lines in following format:

ABC,12345,test.com,56780,0.00,200.65,0.00,0.00,200.65
XYZ,54311,tset.com,69540,0.00,102.32,0.00,0.00,102.32
..
...

I wanted to sort this file on field6 so that i could extract my desired lines from the csv file. I did use below command which sorted my csv file on field no 6:

sort -n -r -t, +6 -7 vishnu.csv

-n Specifies numeric field
-r Reverse sorting
-t specifies seperator (here , is a seperator)
+6, -7 specifies column position

sorting the csv file if separator is tab
sort -t $'\t' -k5 -nr filename

List of tables in the Oracle schema

Wanted to find out list of tables in the Oracle schema? We can use any of the following sql query; which will list all the tables in the specified schema of Oracle database.


SELECT * FROM cat;

SELECT TABLE_NAME FROM TABS;
SELECT * FROM user_objects WHERE object_type = 'TABLE';

SELECT TABLE_NAME FROM ALL_ALL_TABLES;

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";
}

Tuesday, July 22, 2008

Zephyr - A Test Management Tool

Recently i got an email from Zephyr regarding their new product launch. Zephyr is basically a Test Management tool aimed at global SME, IT departments and Testing Vendors which helps the testing team to manage their test cases and provide test cases visibility at all levels using a central repository. I checked their product demo which looks cool.
http://www.getzephyr.com/

Sunday, July 20, 2008

Software Testing Life Cycle


Software Testing Life Cycle

From: sunny.deb, 8 months ago





Software Testing Life Cycle


SlideShare Link

Monday, July 14, 2008

Make INSERT statement syntax from a csv file using perl

I need to read a csv file and insert the data from csv to oracle. I created below perl script which will read the csv file line by line and will create INSERT statement accordingly.

#!/usr/bin/perl

$filename = "test.csv";
open(INFILE, "<", $filename)
or die "Can't open $filename for reading: $!\n";
my(@lines) = <INFILE>;
my($line1) = $lines[0];
my($line2) = $lines[1];

print "$line1 \n";
print "$line2 \n";

close(INFILE);

my($tablename) = "mytable";
my($createquery) = "Create table " . $tablename . "(";

my(@var1) = split("\t", $line1);
my(@var2) = split("\t", $line2);
my($i) = 0;
for $item1 (@var1){
chomp($item1);
$createquery = $createquery . $item1 . " ";
$data = $var2[$i++];
print "$item1\t : $data\n";
if(checkData($data) eq "int"){
$createquery = $createquery . "number(10,0), ";
}
elsif(checkData($data) eq "float"){
$createquery = $createquery . "number(10,2), ";
}
else{
$createquery = $createquery . "varchar2(50), ";
}
}
$createquery = substr($createquery,0, -2);
$createquery = $createquery . ");";
print "$createquery\n";

$i = 0;
for $dataline (@lines){
if ( $i == 0){
$i = 1;
next;
}
chomp($dataline);
my(@dataitem) = split("\t", $dataline);
my($insertquery) = "INSERT INTO " . $tablename . " VALUES (";
print "$dataitem\n";
for $items (@dataitem){
if( (checkData($items) eq "int") || (checkData($items) eq "float") ){
$insertquery = $insertquery . $items .",";
}
else{
$insertquery = $insertquery . "\"" . $items . "\"" .",";
}
}
$insertquery = substr($insertquery, 0, -1);
$insertquery = $insertquery . ")";
print "$insertquery\n";
}

sub checkData(){
if(@_[0] =~ /^-?\d+$/){
return "int";
}
elsif(@_[0] =~ /^-?(?:\d+(?:\.\d*)?|\.\d+)$/){
return "float";
}
else{
return "string";
}
}

Thursday, July 10, 2008

Make CREATE TABLE syntax from a csv file using perl

I have a csv file and i have to make the CREATE TABLE statement (which later will be used to create an Oracle table) by reading first and second line of the csv file. First line in the csv file is column headers and the second line is actual data. By reading the first line, i will create column name and by reading the second line, i'll decide the data type for the column.
Below is the perl script for the same: (i am assuming that data in the csv file is tab seperated)

#!/usr/bin/perl

$filename = "test.csv";
open(INFILE, "<", $filename) or die "Can't open $filename for reading: $!\n";
@lines = <INFILE>;
$line1 = $lines[0];
$line2 = $lines[1];

print "$line1 \n";
print "$line2 \n";

close(INFILE);

$tablename = "mytable";
$query = "Create table " . $tablename . "(";

@var1 = split("\t", $line1);
@var2 = split("\t", $line2);
$i = 0;
for $item1 (@var1){
chomp($item1);
$query = $query . $item1 . " ";
$data = $var2[$i++];
print "$item1\t : $data\n";
if($data =~ /^-?\d+$/){
$query = $query . "number(10,0), ";
}
elsif ($data =~ /^-?(?:\d+(?:\.\d*)?|\.\d+)$/){
$query = $query . "number(10,2), ";
}
else{
$query = $query . "varchar2(50), ";
}
}
$query = substr($query,0, -2);
$query = $query . ");";
print "$query\n";

Tuesday, July 8, 2008

Read data from a csv file using perl (when the column count is not known)

I need to read a csv file, and process each and every column data (i do not know the column count before processing the file)

#!/usr/local/bin/perl

if (scalar(@ARGV) < 1)
{
print "Please Specify the file name to be read \n";
exit
}

$file = $ARGV[0];

open FILE, "< $file" or die "Can't open test.csv : $!";
while(<FILE>){
chop;
my(@columns)= split("\t");
my($colnum)=$#columns;
# print "Number of Column in this row is : $colnum\n";
foreach $col(@columns){
print "$col \t";
}
print "\n";
}
close FILE;

Read data from a csv file using perl (when the column count is known)

I need to read a csv file, and process each and every column data (i know the column count before processing the file)


#!/usr/local/bin/perl

open FILE, "< test.csv" or die "Can't open test.csv : $!";
while(
){
chomp;
($col1,$col2,$col3,$col4) = split ("\t");
print "$col1 \t";
print "$col2 \t";
print "$col3 \t";
print "$col4 \t";
print "\n";
}
close FILE;

Check datatype of a argument in perl

I need to pick few lines from a particular file and check the data type of values of a particular column. Following is the perl script for the same:

#!/usr/bin/perl

$filename = "test.csv";
open(INFILE, "<", $filename) or die "Can't open $filename for reading: $!\n";
@lines =
<INFILE>;
$line1 = $lines[0];
$line2 = $lines[1];

print "$line1 \n";
print "$line2 \n";

close(INFILE);

@var1 = split("\t", $line2);
for $item (@var1){
if($item =~ /\D/){
print "$item\t : Has Non Digits\n";
}
elsif ($item =~ /^\d+$/){
print "$item\t : Whole Number\n";
}
elsif ($item =~ /^-?\d+$/){
print "$item\t : Integer\n";
}
elsif ($item =~ /^[+-]?\d+$/){
print "$item\t : +/- Integer\n";
}
elsif ($item =~ /^-?\d+\.?\d*$/){
print "$item\t : Real Number\n";
}
elsif ($item =~ /^-?(?:\d+(?:\.\d*)?|\.\d+)$/){
print "$item\t : Float Number\n";
}
else{
print "$item\t : NAN\n";
}
}

Print particular line/s from a file using perl

Method 1:

#!/usr/bin/perl

$filename = "test.csv";
open(INFILE, "<", $filename)
or die "Can't open $filename for reading: $!\n";

$line_number = 1;
while () {
$line = $_;
last if $. == $line_number;
}
if ($. != $line_number) {
die "Didn't find line $line_number in $filename\n";
}
print;

close(INFILE);



Method 2:

#!/usr/bin/perl

$filename = "test.csv";
open(INFILE, "<", $filename)
or die "Can't open $filename for reading: $!\n";
@lines = ;
$line1 = $lines[0];
$line2 = $lines[1];

print "$line1 \n";
print "$line2 \n";

close(INFILE);

Friday, June 27, 2008

Set Terminal Title

If you want the Terminal window title to be set automatically to the remote zone you have logged into, add this to your .bashrc file on the remote machine.


# Terminal settings
PS1="[\u@\h \W]# "

if [ -n "$PS1" ]; then
echo -n -e "\033]0;`hostname`\007"
fi

Saturday, June 14, 2008

TNSNAMES.ORA file

TNSNAMES.ORA is a configuration file that defines databases addresses for establishing connections to the database. It resides in ORACLE HOME\NETWORK\ADMIN directory. Below is the sample entry in TNSNAMES.ORA

<addressname> =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(Host = <hostname>)(Port = <port>))
)
(CONNECT_DATA =
(SERVICE_NAME = <sid>)
)
)

Wednesday, June 11, 2008

Read data from a file in perl

Below is the sample perl script, if you want to read some data from a file and pass it to as a argument in your perl script.

In my case, I have some object ids in a file and for each id I have to run oocheck command.

#!/usr/local/bin/perl

open FILE, "testoids" or die $!;

while ()

{

chomp $_;

systemCmd("oocheck -id $_");

}

close(FILE);

sub systemCmd {

my($cmd) = @_;

print("$cmd\n");

(system($cmd) == 0) || die ("cmd $cmd failed");

}

Friday, June 6, 2008

Linux time command

The time command runs the specified program command with the given arguments. When command finishes, time writes a message to standard output giving timing statistics about this program run.

See below example:

[vishnu@solaris /mnt/usr/vishnu] time myProgram arg1

real 24m10.951s

user 6m2.390s

sys 0m15.705s

[vishnu@solaris /mnt/usr/vishnu]

Above command outputs the time taken by myProgram.

· real - Elapsed time from beginning to end of program

· user - time used by the program itself and any library subroutines it calls

· sys- time used by the system calls invoked by the program (directly or indirectly)

Thursday, May 15, 2008

Forgot to mention subject in mail ???

Forgot to mention subject, while writing an official mail ??

Yes.... It's a concern for all.... A mail without a subject brings a bad impression on us.

To avoid this just follow the simple steps mentioned below and see the result


Steps:
1. Open your outlook

2. Press Alt+F11. This opens the Visual Basic editor and then Press Ctrl+R which in turn open Project-Project 1 (left side)

3. On the Left Pane, one can see "Microsoft Outlook Objects" or "Project1", expand this. Now one can see the "This Outlook Session".

4. Double click on "ThisOutLookSession". It will open up a code pane on the right hand side.

5. Copy and Paste the following code in the right pane. (Code Pane) and save it

Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)
Dim strSubject As String
strSubject = Item.Subject
If Len(Trim(strSubject)) = 0 Then
Prompt$ = "Subject is Empty. Are you sure you want to send the Mail?"
If MsgBox(Prompt$, vbYesNo + vbQuestion + vbMsgBoxSetForeground, "Check for Subject") = vbNo Then
Cancel = True
End If
End If
End Sub

6. Now whenever u try to send a mail without subject, which will raise a pop-up to remind you.

Wednesday, April 23, 2008

List only Directory/Files in ls command

ls -l (include both directories and files)

ls -l | grep -v ^d (include only files in listing)

ls -l | grep ^d (include only directories in listing)

Tuesday, April 22, 2008

Read latest file in vi editor

In my daily routine on solaris box, i have to read the latest file in vi. For this i have to run below 2 commands:

ls -ltr
vi filename

I get the latest file name with ls -ltr command (last file in the list) and then vi to open this file.

I was sick of using 2 commands for this simple operation, so i thought of using a single command using combination of commands; following are the commands which I used for this operation:

vi `ls -ltr|tail -1|awk -F" " '{print $9}'` (includes directory listing)
vi `ls -ltr|grep -v ^d|tail -1|awk -F" " '{print $9}'` (ignores directory listing)
or
vi `ls -ltr|tail -1|cut -d":" -f2|cut -d" " -f2` (includes directory listing)
vi `ls -ltr|grep -v ^d|tail -1|cut -d":" -f2|cut -d" " -f2` (ignores directory listing)


Thursday, April 3, 2008

Location of firefox cookies ?

All the firefox cookies are stored in cookies.txt at C:\Documents and Settings\Windows login/user name\Application Data\Mozilla\Firefox\Profiles\profile folder

Monday, March 31, 2008

Testplan plugin in Confluence WIKI

Recently in our organization, we started to use Confluence WIKI for documentation purpose. This wiki has a plugin called TestPlan. I liked this plugin very much as it allows us to maintain our test cases and get the test case execution status.
Below is the screenshot of sample testplan:





Below is the wiki markup for above sample:
{testplan:Release includeJiraLinks=false useFailMacro=false}
^Feature1
//This is comment
Test1
Test2
^Feature2
//This is comment
Test3
Test4
{testplan}

Wednesday, March 26, 2008

vi Examples

s/pat/text/ substitute 1st match of pat with text

s/pat/text/g substitute every match of pat with text

s/pat/text/n substitute the nth occurrence of pat with text

:%!sort or :1,$!sort sort current file

:5,10s/foo/bar/2 change the second occurrence of foo with bar on lines 5-10

:map g 1G map g to really run 1G

3J Join next 2 lines to current one

3,9m$ move lines 3 through 9 to the end of the file

ab w/o without when w/o is typed change to without

:?foo?,/bar/d delete from the reverse match of foo until the next match of bar

:g/{/,/}/< shift all lines between, and including, a "{" and a "}" left

:$-4,$d delete last five lines of buffer

:%s/^\(.*\) \(.*\)$/\2 \1/ swap everything before and after the first space

d'' delete from current position to line of last jump

Perl matches Perl

^Perl matches Perl at beginning of line

Perl$ matches Perl at end of line

^Perl$ matches Perl as the only word on line

^$ matches the empty line

^..*$ matches a line with at least one character

.* matches any string of characters including none

^[ ^I]*$ as above but line can also contain spaces and/or tabs(^I)

[pP]erl matches perl or Perl

[aA][nN] matches an, aN, An, AN

p[aeiou]g second letter is a vowel

i[^aeiou]g second letter is not a vowel

p.g second letter is anything

^....$ matches a line with exactly four characters

^\. matches any line beginning with a dot

^\.[0-9a-z] same with a lowercase letter or digit following

^[^\.] matches any line that does not begin with a dot

;$ matches a line ending with a semicolon

figs* matches fig, figs, figss, figsss etc.

[a-z][a-z]* matches one or more lowercase letters

[a-zA-Z] matches any character

[^0-9a-zA-Z] matches any symbol (not a letter or number)

\&ltthe matches the, theater, then

the\> matches the, breathe

\&ltthe/> matches the

:%s/\<./\u&/g turn the first letter of all words to uppercase

:%s/\<[a-z][!-~]*\>/\u&/g as above

:%s/\<[a-z]/\u&/g as above

:%s/.*/\L&/ turn entire file to lowercase

:%s/<[^>]*>//g remove strings from file that start with a less than sign and end with a greater than sign (html tags)

:1,$s/1$/0/g Replace 1 to 0 from each line of the file, if last character of the line is 1

:1,$s/^1/0/g Replace 1 to 0 from each line of the file, if first character of the line is 1

Tuesday, March 11, 2008

see the differences between two branches of CVS

To see all of the changes between two branches

1. checkout the source from HEAD/or branch, CD into it
2. run command cvs -q diff --brief -r brach_to_compare | grep Index

Monday, March 10, 2008

vi environment variables

set
you can customize your environment with this command by typing set var=value, this will set the specified var to value for a scalar variable. For boolean varaibles, use set var to set and set novar to unset. You can see which variables are set by just typing the set by its itself. You can see a list of all variables by typing set all. some environment variables are specific to the ex editor and some are specific to the vi editor.

boolean variables:

autoindent(ai)

begin editing next line at same level of indent-ion as this one.

autowrite(aw)

write current buffer before leaving

exrc(ex)

tells vi/ex if it should read the .exrc file in the current directory(this can be a security risk).

errorbells

editor sends a beep to the terminal when an incorrect

flash

inverse the screen on an error instead of producing a bell

ignorecase(ic)

ignore case of characters in searches.

lisp

enter lisp mode

list

place a $ at the end of each line and a ^I on each tab.

magic

allow ., [, and * to be interpreted as special characters in RE's.

modelines

execute the first and last 5 lines of the file if of the form: ex:command: or vi:command:

number(nu)

number lines in left margin

showmatch(sm)

when closing a paren., brace or bracket; move the visual cursor to opening item to check scope

showmode(smd)

show type of insert mode

wrapscan(ws)

when searching and at bottom of file, continue searching from the top


Scalar variables:

directory

the location of the temporary directory used by vi

paragraphs(para)

macros to signify the beginning of a paragraph

report

vi will notify you if you change more lines than the value of report

sections(sect)

macros to signify the beginning of a section

shell

The shell to use when executing the command :sh or :!

shiftwidth(sw)

number of spaces to to insert on a shift operation

showmatch(sm)

show the match of ) and } when typed

tabstop

the length, in characters, of a tabstop

term

holds the name of the terminal type being used

wrapmargin(wm)

split lines at the column which is equal to the value of wrapmargin

avoid error "Not owner of .exrc or .exrc is group or world writable" in vi

set this environment variable

export EXINIT="set noexrc"

Saturday, March 8, 2008

vi Editor Commands

The VI editor is a screen-based editor used by many Unix users. The VI editor has powerful features to aid programmers, but many beginning users avoid using VI because the different features overwhelm them.

General startup
To use vi: vi
To exit vi and save changes: ZZ or :wq
To exit vi without saving changes: :q!
To enter vi command mode: [esc]
Read the original file back in so that you can start over.: :e!


Counts

A number preceding any vi command tells vi to repeat that command that many times.
Deleting
x delete character under cursor
X delete character before cursor
dd delete line under cursor
dw delete word under cursor
db delete word before cursor
D delete to the end of line from the current cursor position
d^ delete from current cursor position to the beginning of the line
d$ delete from current cursor position to the end of the line

Copy/Paste Text
yy copies line
P paste copied data before cursor
p paste copied data after cursor

Find Commands
? finds a word going backwards
/ finds a word going forwards
f finds a character on the line under the cursor going forward
F finds a character on the line under the cursor going backwards
t find a character on the current line going forward and stop one character before it
T find a character on the current line going backward and stop one character before it
; repeat last f, F, t, T
, repeat last f, F, t, T going backwards
n repeat last search given by ‘/’ or ‘?’
N repeat last search given by ‘/’ or ‘?’ going backwards

Miscellaneous Commands
. repeat last command
u undoes last command issued
U undoes all commands on one line
xp deletes first character and inserts after second (swap)
J join current line with the next line
^G display current line number
% if at one parenthesis, will jump to its mate
mx mark current line with character x
'x find line marked with character x
^^ Go back to last file
READING/WRITING FILES
:r filename Copies filename after cursor in file currently editing
:n Start editing next file in list
:rew rewind file list, start editing 1st file on argument list
:w Saves the current file without quitting

MOVING
:# Move to line #
:$ Move to last line of file


Character/Line Formatting
~ Switch the case of the character under cursor
< Shifts the line upto where to the left by one shiftwidth
<< Shifts the current line to the left, and can be specified with a count
> Shifts the line upto where to the right by one shiftwidth
>> Shifts the current line to the right, and can be specified with a count
J Join the current line with the next one.

SHELL ESCAPE
:!'CMD' Executes CMD as a shell command
:!sh Fork shell in vi; hit ctrl-d to go back to vi

INSERTING
r replace character under cursor with next character typed
R keep replacing character until [esc] is hit
i insert before cursor
I insert from the beginning of line
a append after cursor
A append at end of line
o open line below cursor and enter append mode
O open line above cursor and enter append mode
c change until . "cc" changes the current line
C change to the end of line from the current cursor position
s substitute one character under the cursor and go into insert mode
S change an entire line


Screen Movement
G move to the last line in the file
xG move to line x
z+ move current line to top of screen
z move current line to the middle of screen
z- move current line to the bottom of screen
^F move forward one screen
^B move backward one line
^D move forward one half screen
^U move backward one half screen
^R redraw screen (does not work with vt100 type terminals)
^L redraw screen (does not work with Televideo terminals)

Cursor Movement
h move left
j move down
k move up
l move right
[return] move to the beginning of next line
$ last column on the current line
0 move cursor to the first column on the current line
^ move cursor to the first nonblank column on the current line
w move to the beginning of the previous word or punctuation
W move past the next space
b move to the beginning of the previous word or punctuation mark
B move to the beginning of the previous word, ignores punctuation
e end of next word or punctuation mark
E end of next word, ignoring punctuation
H move cursor to the top of the screen
M move cursor to the middle of the screen
L move cursor to the bottom of the screen
^H move cursor one space to the left
^J move cursor down one line in same column
^M move to the first character on the next line
^N move cursor down one line in same column
^P move cursor up one line in same column
% move cursor to the matching parenthesis or brace
( move cursor to the beginning of a sentence
) move cursor to the beginning of the next sentence
{ move cursor to the preceding paragraph
} move cursor to the next paragraph
| move cursor to the column specified by the count
+ move cursor to the first non-whitespace character in the next line
- move cursor to the first non-whitespace character in the previous line
_ move cursor to the first non-whitespace character in the current line