Tuesday, March 26, 2013

Perl - How to find the sum of digits in a number?

How to find the sum of all the digits in a number or a string? OR How to find the sum of all elements in array? Let us see the different ways how it can be done in Perl?

1. Divide and accumulate:
my $x=3456;
my $sum=0;
while ($x) {
        $sum+=$x%10;
        $x/=10;
}
print $sum;
  The digits are extracted by taking the modulus of the number with 10, and then dividing the number by 10. This is repeated till the original number becomes zero at the end of which the sum is retrieved.

Thursday, March 14, 2013

How to remove leading zeros in a string in Linux?

How to remove leading zeros in a variable or a string?

Let us consider a variable "x" which has the below value :
$ x=0010
$ echo $x
0010
1. Using typeset command of ksh:
$ typeset -LZ x
$ x=0010
$ echo $x
10
   The variable x is declared using the typeset command. The -Z option of typeset will strip the leading zeros present when used along with -L option.

Tuesday, February 26, 2013

Perl - What is __DATA__ ?

What is __DATA__ ? Why is it used?
    Generally, Perl reads data from a file which in the Perl program can be accessed using open and readline functions. However, for users who just want to test something for an urgent requirement, it is pretty boring to put the test data in a file and access it using the open and readline functions. The solution for this : __DATA__.

   Let us consider a sample text file:
$ cat f1.txt
AIX,1
Solaris,2
Unix,3
Linux,4

Tuesday, February 19, 2013

What is the time command in Linux for?

time command in Unix is used to find the time taken by a particular command to execute. This is very useful when we want to time a particular command or a particular script to know the amount of time it consumes. Not only the elapsed time, the time command also tells the amount of time spent in the user and kernel spaces as well.
$ time

real    0m0.000s
user    0m0.000s
sys     0m0.000s
time command output shows 3 different components:
real - The total time elapsed during the command which includes the time taken for the process.
user - The time taken for the process only in the user space. This does not include kernel calls.
sys - The time taken for the process in system space (for kernel related calls )

Tuesday, February 12, 2013

sed - 10 examples to replace / delete / print lines of CSV file

How to use sed to work with a CSV file? Or How to work with any file in which fields are separated by a delimiter?

Let us consider a sample CSV file with the following content:
cat file
Solaris,25,11
Ubuntu,31,2
Fedora,21,3
LinuxMint,45,4
RedHat,12,5

1. To remove the 1st field or column :
$ sed 's/[^,]*,//' file
25,11
31,2
21,3
45,4
12,5
   This regular expression searches for a sequence of non-comma([^,]*) characters and deletes them which results in the 1st field getting removed.