<?xml version="1.0" encoding="UTF-8" standalone="no"?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><rss xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" version="2.0"><channel><title>The UNIX School</title><description>Instructions/Tutorials on Unix/Linux commands, C Programming, Unix Administration , Oracle, PL SQL, Perl, Productivity tips soft skills for newbies and professionals.</description><managingEditor>noreply@blogger.com (Guru Prasad)</managingEditor><pubDate>Thu, 26 Mar 2026 13:17:50 +0530</pubDate><generator>Blogger http://www.blogger.com</generator><openSearch:totalResults xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/">177</openSearch:totalResults><openSearch:startIndex xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/">1</openSearch:startIndex><openSearch:itemsPerPage xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/">25</openSearch:itemsPerPage><link>http://www.theunixschool.com/</link><language>en-us</language><itunes:explicit>no</itunes:explicit><itunes:subtitle>Instructions/Tutorials on Unix/Linux commands, C Programming, Unix Administration , Oracle, PL SQL, Perl, Productivity tips soft skills for newbies and professionals.</itunes:subtitle><itunes:owner><itunes:email>guru@theunixschool.com</itunes:email></itunes:owner><item><title>Linux Shell - What is IFS?</title><link>http://www.theunixschool.com/2020/05/linux-shell-what-is-ifs.html</link><category>bash</category><category>ksh</category><category>shell script</category><category>special variable IFS</category><pubDate>Tue, 19 May 2020 11:15:00 +0530</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-1255024703457423340.post-643308423712087299</guid><description>&amp;nbsp;IFS stands for internal field separator. This is the delimiter used when words are split.&lt;br /&gt;
&lt;br /&gt;
The man page of bash tells :&lt;br /&gt;
&lt;br /&gt;
&lt;i&gt;IFS&amp;nbsp; &amp;nbsp; The Internal Field Separator that is used for word splitting after expansion and to split lines into&lt;/i&gt;&lt;br /&gt;
&lt;i&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; words with the read builtin command.&amp;nbsp; The default value is ``&amp;lt;space&amp;gt;&amp;lt;tab&amp;gt;&amp;lt;newline&amp;gt;''.&lt;/i&gt;&lt;br /&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
The default value of IFS is a space, a tab followed by a newline.&lt;/div&gt;
&lt;pre class="gpr1"&gt;guru@unixschool:~$ echo "$IFS"
  

guru@unixschool:~$ echo "$IFS" | cat -tve
 ^I$
$
guru@unixschool:~$ 
&lt;/pre&gt;
&amp;nbsp; When we echoed IFS for the first time, we could not see anything becuase they are special characters. On using the &lt;i&gt;tve&lt;/i&gt; options of cat, we can see a space, followed by a &lt;i&gt;^I&lt;/i&gt; which is a tab character and then followed by a newline.&lt;br /&gt;
&lt;a name='more'&gt;&lt;/a&gt;&lt;br /&gt;
&lt;b&gt;1. Variable with space separated values&lt;/b&gt;:
&lt;br /&gt;
&lt;pre class="gpr1"&gt;guru@unixschool:~$ var="hi 25 hello"
&lt;/pre&gt;
We have declared a variable &lt;i&gt;var&lt;/i&gt; with space separated values. Now, lets use for loop at the prompt itself to access the individual values:
&lt;br /&gt;
&lt;pre class="gpr1"&gt;guru@unixschool:~$ var="hi 25 hello"
guru@unixschool:~$ for i in $var
&amp;gt; do
&amp;gt;   echo $i
&amp;gt; done
hi
25
hello
guru@unixschool:~$ 
&lt;/pre&gt;
If you notice, the values got separated with the space as delimiter and the variable &lt;i&gt;i&lt;/i&gt; got each value in every iteration.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;2. Variable with tab separated values &lt;/b&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;guru@unixschool:~$ var="hi      25      hello"
guru@unixschool:~$ echo $var
hi 25 hello
guru@unixschool:~$ echo "$var" | cat -tve
hi^I25^Ihello$
guru@unixschool:~$ 
guru@unixschool:~$ for i in $var
&amp;gt; do
&amp;gt;  echo $i
&amp;gt; done
hi
25
hello
guru@unixschool:~$ 
&lt;/pre&gt;
As shown above, the values got separated with tab as delimiter . And the value of &lt;i&gt;i&lt;/i&gt; got each one in subsequent iterations. Please note when we print $var, we cannot see the tabs, only when you pipe with &lt;i&gt;cat&lt;/i&gt; and use the &lt;i&gt;tve&lt;/i&gt; option, we can.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;3. Variable with values separated by a new line character&lt;/b&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;guru@unixschool:~$ var="hi
&amp;gt; 25
&amp;gt; hello"
guru@unixschool:~$ 
guru@unixschool:~$ echo "$var"
hi
25
hello
guru@unixschool:~$ for i in $var
&amp;gt; do
&amp;gt;  echo $i
&amp;gt; done
hi
25
hello
guru@unixschool:~$ 
&lt;/pre&gt;
Like in earlier cases, the values got separated now with newline as delimiter.&lt;br /&gt;
&amp;nbsp; &amp;nbsp;Basically, shell splits the value of variable as what is the value is IFS special variable. Since IFS has space, tab and newline, the variables will get split with any/all of them as&amp;nbsp; a delimiter.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;4. Variable with comma separated values&lt;/b&gt;:&lt;br /&gt;
&amp;nbsp; Similarly, if we want to split a variable on the basis of comma, simply set it to IFS.&lt;br /&gt;
&lt;pre class="gpr1"&gt;guru@unixschool:~$ IFS=","
guru@unixschool:~$ var="hi,hello,world"
guru@unixschool:~$ 
guru@unixschool:~$ for i in $var
&amp;gt; do
&amp;gt;   echo $i
&amp;gt; done
hi
hello
world
guru@unixschool:~$ 
&lt;/pre&gt;
As seen , the variables now got split with comma as separator the moment we set the IFS to comma.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;5. Default IFS vs Custom IFS&lt;/b&gt;:&lt;br /&gt;
But there is a difference with the default IFS and the IFS value set by the user. In case of default IFS, the shell tries to separate taking into account sequence of spaces, sequence of tabs as one single separator, whereas it is not the case with user set separator.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;5a. Variable with more spaces&lt;/b&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;guru@unixschool:~$ var="hi 25     hello  "
guru@unixschool:~$ 
guru@unixschool:~$ for i in $var
&amp;gt; do
&amp;gt;   echo [$i]
&amp;gt; done
[hi]
[25]
[hello]
guru@unixschool:~$ 
&lt;/pre&gt;
If you notice, the shell considered the entire set of spaces as one delimiter. Square brackets are used to capture the variable value as is.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;5b. Variable with multiple commas&lt;/b&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;guru@unixschool:~$ var="hi,25,,,hello "
guru@unixschool:~$ IFS=,
guru@unixschool:~$ for i in $var
&amp;gt; do
&amp;gt;   echo [$i]
&amp;gt; done
[hi]
[25]
[]
[]
[hello ]
guru@unixschool:~$ 
&lt;/pre&gt;
As seen above, the shell took each comma as a separate delimiter unlike taking sequence of commas as it happened in case of default IFS. Due to this, we got empty some values, and also notice the space in the last value.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;6. Reading a file with custom IFS&lt;/b&gt;:&lt;br /&gt;
Let us have a multi line file with a colon delimiter :&lt;br /&gt;
&lt;pre class="gpr1"&gt;guru@unixschool:~$ cat user.txt 
guru:x:1001:1001:guru,,,:/home/guru:/bin/bash
oracle:x:1002:1002::/u01/app/oracle:/bin/bash
test:x:1003:1003::/home/test:/bin/bash
guru@unixschool:~$ 
&lt;/pre&gt;
&amp;nbsp;Now, we will have a script to parse the file using colon as IFS:&lt;br /&gt;
&lt;b&gt;6a. Reading into multiple variables&lt;/b&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;#!/bin/bash
  
IFS=":"
while read user home_dir shell
do
    echo "User : $user , Home Dir : $home_dir"
done &amp;lt; $HOME/user.txt
&lt;/pre&gt;
Output:
&lt;br /&gt;
&lt;pre class="gpr1"&gt;User : guru , Home Dir : /home/guru
User : oracle , Home Dir : /u01/app/oracle
User : test , Home Dir : /home/test
&lt;/pre&gt;
&amp;nbsp;Once the IFS is set to colon, the read started reading each value with colon as delimiter and read the individual values in user, home_dir and shell variables.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;6b. Reading into an array&lt;/b&gt;:&lt;br /&gt;
&amp;nbsp; Instead of reading into multiple variables, we can also read into an array:&lt;br /&gt;
&lt;pre class="gpr1"&gt;#!/bin/bash
  
IFS=":"
while read -a arr
do
    echo "User : ${arr[0]} , Home Dir : ${arr[1]}"
done &amp;lt; $HOME/user.txt
&lt;/pre&gt;
&lt;br /&gt;
By using -a option of read, the values got read into &lt;a href="http://www.theunixschool.com/2017/01/how-to-use-arrays-in-ksh.html"&gt;arrays&lt;/a&gt;.</description><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><author>guru@theunixschool.com (Guru Prasad)</author></item><item><title>Python - How does an iterator work</title><link>http://www.theunixschool.com/2020/05/python-how-does-iterator-work.html</link><category>python iterator</category><category>python3</category><pubDate>Thu, 14 May 2020 11:17:00 +0530</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-1255024703457423340.post-8305908039624076353</guid><description>&amp;nbsp;In this article, we will discuss how does an iterator work.&amp;nbsp; Python has 2 function related to iterator: &lt;i&gt;iter&lt;/i&gt; and &lt;i&gt;next&lt;/i&gt;. &lt;i&gt;iter&lt;/i&gt; creates an iteration object for the requested input, and the &lt;i&gt;next&lt;/i&gt; function returns the next element present in the iterator. &lt;i&gt;next&lt;/i&gt; keeps on returning till the last element is reached.&lt;br /&gt;
&lt;br /&gt;
&amp;nbsp; &amp;nbsp;Let us create an iterator for a list and see how the &lt;i&gt;next&lt;/i&gt; and &lt;i&gt;iter &lt;/i&gt;function works:&lt;br /&gt;
&lt;pre class="gpr1"&gt;&amp;gt;&amp;gt;&amp;gt; l1 = [2,25,33,12]
&amp;gt;&amp;gt;&amp;gt; l1
[2, 25, 33, 12]
&amp;gt;&amp;gt;&amp;gt; it1 = iter(l1)
&amp;gt;&amp;gt;&amp;gt; it1
&amp;lt;list_iterator object at 0x7fc24f93aa58&amp;gt;
&amp;gt;&amp;gt;&amp;gt; next(it1)
2
&amp;gt;&amp;gt;&amp;gt; next(it1)
25
&amp;gt;&amp;gt;&amp;gt; next(it1)
33
&amp;gt;&amp;gt;&amp;gt; next(it1)
12
&amp;gt;&amp;gt;&amp;gt; next(it1)
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
StopIteration
&amp;gt;&amp;gt;&amp;gt; 
&lt;/module&gt;&lt;/stdin&gt;&lt;/pre&gt;
When we printed &lt;i&gt;it1&lt;/i&gt;, it shows it as an &lt;i&gt;list_iterator&lt;/i&gt; object. Everytime &lt;i&gt;next&lt;/i&gt; is hit, it gave the next element and finally when there are no more elements, it gives &lt;i&gt;StopIteration&lt;/i&gt;.
&lt;br /&gt;
&lt;a name='more'&gt;&lt;/a&gt;&lt;br /&gt;
When we hit iter, it actually calls &lt;i&gt;__iter__&lt;/i&gt; method of the corresponding class. Meaning when we call &lt;i&gt;iter&lt;/i&gt; on a list, it will call &lt;i&gt;__iter__&lt;/i&gt; of the list class.&amp;nbsp; Similarly, when we hit &lt;i&gt;next&lt;/i&gt; on an object, it calls the &lt;i&gt;__next__&lt;/i&gt; of the corresponding object.&lt;br /&gt;
&lt;br /&gt;
&amp;nbsp; &amp;nbsp;Let us write a test class and have &lt;i&gt;__iter__ &lt;/i&gt;and &lt;i&gt;__next__&amp;nbsp;&lt;/i&gt;methods:
&lt;script src="https://gist.github.com/guruprasadpr/4ec20c9b4aaf3096c6795d6653d2ab35.js"&gt;&lt;/script&gt;
&amp;nbsp;This class takes a list as input and assigns it to data variable. The &lt;i&gt;__iter__&lt;/i&gt;method simply returns the reference. The &lt;i&gt;__next_&lt;/i&gt;_ method returns the next available data element and increments the index by 1 after every iteration. And on finally reaching the maximum, the &lt;i&gt;StopIteration&lt;/i&gt; exception is thrown.&lt;br /&gt;
&lt;br /&gt;
Let us run and check:
&lt;br /&gt;
&lt;pre class="gpr1"&gt;&amp;gt;&amp;gt;&amp;gt; from iterator import TestIterator
&amp;gt;&amp;gt;&amp;gt; t1 = TestIterator([2, 25, 33])
&amp;gt;&amp;gt;&amp;gt; t1
&amp;lt;iterator.TestIterator object at 0x7f5782d4ea90&amp;gt;
&amp;gt;&amp;gt;&amp;gt; next(t1)
2
&amp;gt;&amp;gt;&amp;gt; next(t1)
25
&amp;gt;&amp;gt;&amp;gt; next(t1)
33
&amp;gt;&amp;gt;&amp;gt; next(t1)
Traceback (most recent call last):
  File "&amp;lt;stdin&amp;gt;", line 1, in &amp;lt;module&amp;gt;
  File "/home/guru/iterator.py", line 13, in __next__
    raise StopIteration()
StopIteration
&amp;gt;&amp;gt;&amp;gt; 
&lt;/pre&gt;
&amp;nbsp; When the object &lt;i&gt;t1&lt;/i&gt; is created, it is showing as iterator.TestIterator object. On subsequent calls to &lt;i&gt;next&lt;/i&gt; function, the &lt;i&gt;__next__&lt;/i&gt; method gets called and we get the subsequent values. Its this simple to have our own iterator.&lt;br /&gt;
&lt;pre class="gpr1"&gt;&amp;gt;&amp;gt;&amp;gt; t1 = TestIterator([2, 25, 33])
&amp;gt;&amp;gt;&amp;gt; t2 = iter(t1)
Iter got called
&amp;gt;&amp;gt;&amp;gt; t2
&amp;lt;iterator.TestIterator object at 0x7f5782d4ec88&amp;gt;
&amp;gt;&amp;gt;&amp;gt; 
&lt;/pre&gt;
&amp;nbsp; As seen here, on calling iter, the &lt;i&gt;__iter__&lt;/i&gt; method got called.</description><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><author>guru@theunixschool.com (Guru Prasad)</author></item><item><title>bash - 5 examples to do arithmetic operations</title><link>http://www.theunixschool.com/2020/05/bash-5-examples-to-do-arithmetic.html</link><category>bash</category><category>bash arithmetic</category><pubDate>Tue, 5 May 2020 12:16:00 +0530</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-1255024703457423340.post-6948872954256241493</guid><description>&amp;nbsp;While working in bash or while writing bash scripts, many times it so happens we rely on &lt;a href="http://www.theunixschool.com/2012/03/internal-vs-external-commands.html"&gt;external&lt;/a&gt; commands to get our math done. Most of the arithmetic can be handled by the bash itself.&amp;nbsp; &amp;nbsp;In this article, we will see how to do arithmetic operations in bash.&lt;br /&gt;
&lt;br /&gt;
1&lt;b&gt;. Add / Subtract numbers&lt;/b&gt;:&lt;br /&gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp;One common way to basic arithmetic using bash is by using the &lt;i&gt;let&lt;/i&gt; command.
&lt;br /&gt;
&lt;pre class="gpr1"&gt;x=20
y=30
let z=x+y
echo "z is $z"
&lt;/pre&gt;
&amp;nbsp; This is purely a shell operation without any external command. This way one can do for subtract(/), multiply(*), divide(/) and remainder(%) operation.
&lt;br /&gt;
&lt;pre class="gpr1"&gt;x=20
y=30
((z=x+y))
echo "z is $z"
&lt;/pre&gt;
&amp;nbsp; The other way to do is using the &lt;i&gt;((expression))&lt;/i&gt; where the expression is an arithmetic one. Using this double brace notation, all the bash arithmetic can be done.&lt;br /&gt;
&amp;nbsp; &amp;nbsp;Bash also allows to use +=, -= operators like in many programming languages. So, if we have something like x=x+10, it can be written as
&lt;br /&gt;
&lt;pre class="gpr1"&gt;x=40
((x+=10))
echo "x is $x"
&lt;/pre&gt;
&lt;a name='more'&gt;&lt;/a&gt;&lt;b&gt;2. Unary operator&lt;/b&gt;:&lt;br /&gt;
&amp;nbsp; &amp;nbsp;Bash has the unary operator ++ and -- . In the below example, the value of x is being incremented by 1. It is equivalent to writing &lt;i&gt;x=x+1&lt;/i&gt;.&lt;br /&gt;
&lt;pre class="gpr1"&gt;x=40
((x++))
echo "x is $x"
&lt;/pre&gt;
&lt;b&gt;3. Conditional&lt;/b&gt;:&lt;br /&gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;Bash has a C program like syntax when it comes for condition checking using if block.
&lt;br /&gt;
&lt;pre class="gpr1"&gt;x=20
y=30
if (( x &amp;gt; y ))
then
    echo "$x is bigger"
else
    echo "$y is bigger"
fi
&lt;/pre&gt;
If you notice above, we did not use &lt;i&gt;$&lt;/i&gt; infront of the variables &lt;i&gt;x&lt;/i&gt; or &lt;i&gt;y&lt;/i&gt;. Within the bracket notations, we refer to the variable directly.&lt;br /&gt;
&lt;b&gt;&lt;br /&gt;&lt;/b&gt;
&lt;b&gt;4. Logical Operator&lt;/b&gt;:&lt;br /&gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;Bash provides both the logical AND and logical OR like other programming languages.
&lt;br /&gt;
&lt;pre class="gpr1"&gt;x=20
y=30
if ((x &amp;gt; 10)) &amp;amp;&amp;amp; (( x &amp;gt; y ))
then
    echo "x is bigger"
else
    echo "y is bigger"
fi
&lt;/pre&gt;
We are comparing more than one condition here using logical &lt;i&gt;&amp;amp;&amp;amp;&lt;/i&gt;. The condition will be true only when both the condition are true. Similarly, for logical OR, we use &lt;i&gt;||&lt;/i&gt;.&lt;br /&gt;
&lt;b&gt;&lt;br /&gt;&lt;/b&gt;
&lt;b&gt;5. Ternary operator&lt;/b&gt;:&lt;br /&gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; Bash has an exact C like ternary operator too.
&lt;br /&gt;
&lt;pre class="gpr1"&gt;x=40
y=50
((z=(x&amp;gt;y)?100:200))
echo $z
&lt;/pre&gt;
&amp;nbsp;If &lt;i&gt;x&lt;/i&gt; is greater than &lt;i&gt;y&lt;/i&gt;, &lt;i&gt;100&lt;/i&gt; is assigned to &lt;i&gt;z&lt;/i&gt;, else &lt;i&gt;200&lt;/i&gt; is assigned.&lt;br /&gt;
&lt;br /&gt;
Note: Bash does not support floating point operations. To deal with floating point arithmetic, we can make use of the &lt;a href="http://www.theunixschool.com/2011/05/bc-unix-calculator.html"&gt;bc command&lt;/a&gt;.</description><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><author>guru@theunixschool.com (Guru Prasad)</author></item><item><title>Python - How to read a file?</title><link>http://www.theunixschool.com/2020/04/python-how-to-read-file.html</link><category>python</category><category>python read file</category><category>python3</category><pubDate>Thu, 30 Apr 2020 08:40:00 +0530</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-1255024703457423340.post-8026589050092538656</guid><description>&amp;nbsp; &amp;nbsp;In this article, we will see how to read from a file. Let us have file with content as below:&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ cat file
Unix
Linux
AIX
&lt;/pre&gt;
&lt;b&gt;1.&amp;nbsp; Reading line by line&lt;/b&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;&amp;gt;&amp;gt;&amp;gt; fd = open('/home/guru/file', 'r')
&amp;gt;&amp;gt;&amp;gt; for line in fd:
...   print(line)
... 
Unix

Linux

AIX

&amp;gt;&amp;gt;&amp;gt; 
&lt;/pre&gt;
&lt;div&gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;&lt;i&gt;open&lt;/i&gt; function opens a file and returns a file object.&amp;nbsp; Arguments are filename and the mode, 'r' for reading.&amp;nbsp; When the file object is traversed, every iteration reads a line and line gets printed. Notice the blank line after every print. This is because the variable line contains a newline character read from the file and print function adds another newline.&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;
&lt;a name='more'&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div&gt;
&amp;nbsp; One way to remove the blank line is by suppressing the print function to print without newline. This is done by passing an empty value to &lt;i&gt;end&lt;/i&gt;. Since, the default mode is read, it can be removed.&amp;nbsp;&lt;/div&gt;
&lt;pre class="gpr1"&gt;&amp;gt;&amp;gt;&amp;gt; fd = open('/home/guru/file')
&amp;gt;&amp;gt;&amp;gt; for line in fd:
...   print(line, end='')
... 
Unix
Linux
AIX
&amp;gt;&amp;gt;&amp;gt; 
&lt;/pre&gt;
&lt;div&gt;
&amp;nbsp; &amp;nbsp;Another way to not print empty line is to ensure the newline character is stripped from the line variable using the &lt;i&gt;strip&lt;/i&gt; function.&amp;nbsp;&lt;/div&gt;
&lt;pre class="gpr1"&gt;&amp;gt;&amp;gt;&amp;gt; fd = open('/home/guru/file')
&amp;gt;&amp;gt;&amp;gt; for line in fd:
...   print(line.strip())
... 
Unix
Linux
AIX
&amp;gt;&amp;gt;&amp;gt; &lt;/pre&gt;
&lt;b&gt;2. Reading using readline &lt;/b&gt;:
&lt;br /&gt;
&lt;div&gt;
&amp;nbsp; &amp;nbsp;readline function reads one line at a time. Once the end of the file has reached, it returns empty string.&lt;/div&gt;
&lt;pre class="gpr1"&gt;&amp;gt;&amp;gt;&amp;gt; fd = open('/home/guru/file')
&amp;gt;&amp;gt;&amp;gt; fd.readline()
'Unix\n'
&amp;gt;&amp;gt;&amp;gt; fd.readline().strip()
'Linux'
&amp;gt;&amp;gt;&amp;gt; fd.readline().strip()
'AIX'
&amp;gt;&amp;gt;&amp;gt; fd.readline().strip()
''
&amp;gt;&amp;gt;&amp;gt; 
&lt;/pre&gt;
&lt;b&gt;3. Read using readlines&lt;/b&gt;:
&lt;br /&gt;
&lt;pre class="gpr1"&gt;&amp;gt;&amp;gt;&amp;gt; fd = open('/home/guru/file')
&amp;gt;&amp;gt;&amp;gt; for line in fd.readlines():
...   print(line.strip())
... 
Unix
Linux
AIX
&amp;gt;&amp;gt;&amp;gt; &lt;/pre&gt;
&lt;i&gt;readlines&lt;/i&gt; reads the entire file and returns a list.&lt;br /&gt;
&lt;br /&gt;
&lt;div&gt;
&lt;b&gt;4. Read a file into a list&lt;/b&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;&amp;gt;&amp;gt;&amp;gt; fd = open('/home/guru/file')
&amp;gt;&amp;gt;&amp;gt; l1 = fd.readlines()
&amp;gt;&amp;gt;&amp;gt; l1
['Unix\n', 'Linux\n', 'AIX\n']
&lt;/pre&gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp;Since &lt;i&gt;readlines&lt;/i&gt; returns a list, it can directly be assigned to a list variable.&amp;nbsp; However, it has newline characters at the end.&lt;br /&gt;
&lt;pre class="gpr1"&gt;&amp;gt;&amp;gt;&amp;gt; l1 = map(str.strip,fd.readlines())
&amp;gt;&amp;gt;&amp;gt; list(l1)
['Unix', 'Linux', 'AIX']
&amp;gt;&amp;gt;&amp;gt; 
&lt;/pre&gt;
&lt;div&gt;
&amp;nbsp; &amp;nbsp;Using &lt;i&gt;map&lt;/i&gt;, we strip off the newline characters of every element from the list using the &lt;i&gt;strip&lt;/i&gt; function.&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;b&gt;List comprehension&lt;/b&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;&amp;gt;&amp;gt;&amp;gt; fd = open('/home/guru/file')
&amp;gt;&amp;gt;&amp;gt; [ line for line in fd ]
['Unix\n', 'Linux\n', 'AIX\n']
&amp;gt;&amp;gt;&amp;gt; 
&lt;/pre&gt;
With newline characters stripped, 
&lt;br /&gt;
&lt;pre class="gpr1"&gt;&amp;gt;&amp;gt;&amp;gt; [ line.strip() for line in fd ]
['Unix', 'Linux', 'AIX']
&amp;gt;&amp;gt;&amp;gt; 
&lt;/pre&gt;
&lt;b&gt;5. Read a file using read function:&lt;/b&gt;&lt;br /&gt;
&amp;nbsp; &amp;nbsp; &lt;i&gt;read&lt;/i&gt; function reads the entire file and returns a string.
&lt;br /&gt;
&lt;pre class="gpr1"&gt;&amp;gt;&amp;gt;&amp;gt; fd = open('/home/guru/file')
&amp;gt;&amp;gt;&amp;gt; fd.read()
'Unix\nLinux\nAIX\n'
&lt;/pre&gt;
&amp;nbsp; &amp;nbsp;By stripping the newline characters from the string, it can be converted to a list.&lt;br /&gt;
&lt;pre class="gpr1"&gt;&amp;gt;&amp;gt;&amp;gt; fd.seek(0)
0
&amp;gt;&amp;gt;&amp;gt; fd.read().split('\n')
['Unix', 'Linux', 'AIX', '']
&amp;gt;&amp;gt;&amp;gt; 
&lt;/pre&gt;
&amp;nbsp; &amp;nbsp;Notice the extra element, an empty one at the end. It is due to the last newline character. Once &lt;i&gt;read&lt;/i&gt; is called, the file object reaches to the end of the file. In order to read again, we have to take the file to the beginning which is done using &lt;i&gt;seek&lt;/i&gt; function.&lt;br /&gt;
&lt;pre class="gpr1"&gt;&amp;gt;&amp;gt;&amp;gt; fd.seek(0)
0
&amp;gt;&amp;gt;&amp;gt; fd.read().strip().split('\n')
['Unix', 'Linux', 'AIX']
&amp;gt;&amp;gt;&amp;gt; 
&amp;gt;&amp;gt;&amp;gt; fd.closed
False
&amp;gt;&amp;gt;&amp;gt; fd.close()
&amp;gt;&amp;gt;&amp;gt; 
&lt;/pre&gt;
&lt;div&gt;
&amp;nbsp; &amp;nbsp;By stripping the newline before doing split, we will get the correct result. &lt;i&gt;closed&lt;/i&gt; tells whether a file is closed or not. We always have to manually close the file using &lt;i&gt;close&lt;/i&gt; function.&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;b&gt;6. Reading with 'with open' &lt;/b&gt;:&lt;/div&gt;
&lt;div&gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; Python3 came up with a new 'with open' syntax for file handling.&amp;nbsp;&lt;/div&gt;
&lt;pre class="gpr1"&gt;&amp;gt;&amp;gt;&amp;gt; with open('/home/guru/file') as fd:
...   for line in fd:
...     print(line.strip())
... 
Unix
Linux
AIX
&amp;gt;&amp;gt;&amp;gt; fd.closed
True
&amp;gt;&amp;gt;&amp;gt; 
&lt;/pre&gt;
&amp;nbsp; &amp;nbsp;The advantage of this is file is automatically closed after reading. This is true even if an exception occurs.
</description><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><author>guru@theunixschool.com (Guru Prasad)</author></item><item><title>bash - 10 examples to find / replace in a string </title><link>http://www.theunixschool.com/2020/04/bash-10-examples-to-find-replace-in.html</link><category>bash</category><category>sed</category><category>sed regular expression</category><category>sed replace</category><pubDate>Tue, 28 Apr 2020 05:47:00 +0530</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-1255024703457423340.post-7623817896821752744</guid><description>Many times when we want to replace or extract something, we immediately end up with and awk or a sed oneliner. Keep in mind, the first option should always be a internal shell option, only in the absence of which we should resort to an &lt;a href="http://www.theunixschool.com/2012/03/internal-vs-external-commands.html"&gt;external command&lt;/a&gt;. In this article, we will see 10 different examples where instead of an &lt;a href="http://www.theunixschool.com/p/awk-sed.html"&gt;awk/sed&lt;/a&gt;, using bash specific internal will be very beneficial:&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;1. Capitalize a string&lt;/b&gt;:&amp;nbsp; Though there are many &lt;a href="http://www.theunixschool.com/2012/03/different-ways-to-capitalize-contents.html"&gt;ways to capitalize a string&lt;/a&gt;,&amp;nbsp; one tends to use toupper function to get it done. Instead, bash can directly handle it.&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ x='hello'
$ echo ${x^^}
HELLO
$ echo "$x" | awk '{print toupper($0)}'
HELLO
&lt;/pre&gt;
&amp;nbsp; &amp;nbsp;This feature of bash(&lt;i&gt;^^&lt;/i&gt;) is only available for bash version 4. The two carrot pattern capitalizes the entire string.&lt;br /&gt;
&lt;a name='more'&gt;&lt;/a&gt;&lt;br /&gt;
&lt;b&gt;2. Capitalize only first character&lt;/b&gt;:
&amp;nbsp; &amp;nbsp; One common way used to get this is using &lt;a href="http://www.theunixschool.com/p/awk-sed.html"&gt;sed&lt;/a&gt;&amp;nbsp;where we match a single character(.) and replace it with uppercase.&amp;nbsp; Bash 4, when used with only carrot(^) capitalizes only first character.&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ x='hello'
$ echo ${x^}
Hello
$ echo "$x" | sed -e "s/./\u&amp;amp;/"
Hello
&lt;/pre&gt;
&lt;b&gt;3. Convert string to lowercase&lt;/b&gt;:&lt;br /&gt;
&amp;nbsp; &amp;nbsp; Bash has another case modification pattern &lt;i&gt;,,&lt;/i&gt; which will change the case to lowercase.&amp;nbsp; Generally, folks try to use tolower of &lt;i&gt;awk&lt;/i&gt; or the &lt;i&gt;tr&lt;/i&gt; command for this.
&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ x='HELLO'
$ echo ${x,,}
hello
$ echo "$x" | awk '{print tolower($0);}'
hello
&lt;/pre&gt;
&lt;b&gt;4. Convert first character to lowercase&lt;/b&gt;:&lt;br /&gt;
&amp;nbsp; When the case modification pattern used is a single comma(&lt;i&gt;,&lt;/i&gt;), only the first character is converted.
&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ x='HELLO'
$ echo ${x,}
hELLO
$ echo "$x" | sed -e "s/./\l&amp;amp;/"
hELLO
&lt;/pre&gt;
&lt;b&gt;5. Replace set of characters to lowercase&lt;/b&gt;:&lt;br /&gt;
&amp;nbsp; &amp;nbsp;Bash's case modification can take a pattern after the double comma or double caret's. When given,the case conversion is done only on the pattern which is matched. In this example, we want to change the case of all E and O to lowercase.
&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ echo ${x,,[EO]}
HeLLo
$ echo "$x" | sed 's/[EO]/\l&amp;amp;/g'
HeLLo
&lt;/pre&gt;
Now if you look at example 3 when we giving without any pattern, it means apply the action on the entire string and hence we got the entire string capitalized.&lt;br /&gt;
&lt;br /&gt;
&amp;nbsp;&lt;b&gt;6. Replace a pattern with another pattern&lt;/b&gt;:&lt;br /&gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp;Bash has an inbuilt substitution option where we can replace a pattern with another. In this case, to replace 'a' with 'A', we use it like below. Most of the times we go for sed by default when it comes to string repalcement like this:
&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ x='Rama and Sita'
$ echo ${x/a/A}
RAma and Sita
$ echo "$x" | sed 's/a/A/'
RAma and Sita
&lt;/pre&gt;
The above replaced only the 1st instance of the match. To replace all instances, the pattern should start with a &lt;i&gt;/ &lt;/i&gt;&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ echo ${x//a/A}
RAmA And SitA
$ echo "$x" | sed 's/a/A/g'
RAmA And SitA
&lt;/pre&gt;
&lt;b&gt;7. Replace a pattern with another&lt;/b&gt;:&lt;br /&gt;
&amp;nbsp; &amp;nbsp;Bash allows to use wildcards in the pattern match. In the below example, we want to replace everything starting from a digit with a pattern "old".
&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ x='Ram is 24 years old'
$ echo ${x/[0-9]*/ old}
Ram is old
$ echo "$x" | sed 's/[0-9].*/old/'
Ram is old
&lt;/pre&gt;
&lt;b&gt;8. Extract filename from absolute path&lt;/b&gt;:&lt;br /&gt;
&amp;nbsp; &amp;nbsp;Bash's, remove matching prefix pattern, &lt;i&gt;##&lt;/i&gt;, removes the longest matching pattern from the beginning. The pattern we have given is &lt;i&gt;*/&lt;/i&gt; meaning an set of characters followed by &lt;i&gt;/&lt;/i&gt;. Since we have asked for longest match, it will remove till the last &lt;i&gt;/&lt;/i&gt;.
&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ echo "$x" | awk -F'/' '{print $NF}'
test.csv
$ x='/home/guru/test.csv'
$ echo ${x##*/}
test.csv
$ echo "$x" | awk -F'/' '{print $NF}'
test.csv
&lt;/pre&gt;
&lt;b&gt;9. Extract directory from absolute path&lt;/b&gt;:&lt;br /&gt;
&amp;nbsp; &amp;nbsp;Bash's, remove matching suffix pattern, &lt;i&gt;%&lt;/i&gt;, removes the smallest matching pattern from the end. In this case, the pattern &lt;i&gt;/*&lt;/i&gt; indicates a slash followed by set of characters. Since we have asked for shortest match, it will remove &lt;i&gt;/test.csv&lt;/i&gt;, as a result we get the directory.
&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ x='/home/guru/test.csv'
/home/guru/
$ echo ${x%/*}/
/home/guru/
$ echo ${x%/*}
/home/guru
&lt;/pre&gt;
&lt;b&gt;10. Remove a pattern from the string&lt;/b&gt;:&lt;br /&gt;
&amp;nbsp; &amp;nbsp; Bash's, remove matching suffix pattern, &lt;i&gt;%%&lt;/i&gt;, removes the longest matching pattern from the end. In this case, the pattern &lt;i&gt;[0-9]*&lt;/i&gt; indicates a number followed by set of characters. Since we have asked for longset match, it will start removing 2 all the way till the end.
&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ x='Ram is 24 and Lax is 50 years old'
$ echo ${x%%[0-9]*}
Ram is
$ echo "$x"  | sed 's/[0-9].*//'
Ram is 
&lt;/pre&gt;
</description><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><author>guru@theunixschool.com (Guru Prasad)</author></item><item><title>Python - How to get the NSE daily data feed?</title><link>http://www.theunixschool.com/2020/04/python-how-to-get-nse-daily-data-feed.html</link><category>alpha vantage</category><category>NSE</category><category>pandas</category><category>python</category><pubDate>Thu, 23 Apr 2020 08:42:00 +0530</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-1255024703457423340.post-4375251953124923676</guid><description>These are days when trading decisions are taken more by a software, and people write algorithms to get their trades executed. For all this to happen, you need to have the stock data feed with you. Data is nothing but the daily open,close,high, low and volume for the stocks. Once you have the feed, the kind of things you can do with that data is endless.&amp;nbsp; In this article, we will see how to download the data feed through a Python program.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Pre-requisites&lt;/b&gt;:&lt;br /&gt;
1. Install pandas if not present already:&lt;br /&gt;
&lt;pre class="gpr1"&gt;pip install pandas&lt;/pre&gt;
2. &lt;a href="https://www.alphavantage.co/"&gt;Alpha Vantage&lt;/a&gt; has exposed free API's for downloading data feed. Install the alpha vantage package:&lt;br /&gt;
&lt;pre class="gpr1"&gt;pip install alpha-vantage&lt;/pre&gt;
3. You need to &lt;a href="https://www.alphavantage.co/support/#api-key"&gt;register&lt;/a&gt; yourself in Alpha vantage and get an API key.&lt;br /&gt;
&lt;a name='more'&gt;&lt;/a&gt;&lt;br /&gt;
&lt;b&gt;Program&lt;/b&gt;:&lt;br /&gt;
Below is the Python program, alpha_data.py, to get the feed:&lt;br /&gt;
&lt;br /&gt;
&lt;script src="https://gist.github.com/guruprasadpr/a996db91a4e709da4fd82e1e5ef71b50.js"&gt;&lt;/script&gt;

&lt;div&gt;
&lt;b&gt;Changes you should do in the script&lt;/b&gt;:&lt;/div&gt;
1. In Line 1, replace the she-bang line with the appropriate one as present in your system.&lt;br /&gt;
2. In Line 7, replace the path in stock_dir to that location in which you want to save your feed files.&lt;br /&gt;
3. In Line 8, replace the file &lt;i&gt;nifty50list.dat&lt;/i&gt; along with path with a file which contains the list of stock names for which you want to get the data feed. One stock per line. Sample below:&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ head -3 /home/guru/history/config/nifty50list.dat
ADANIPORTS
ASIANPAINT
AXISBANK
$ 
&lt;/pre&gt;
4. In Line 10, replace the value of key with the value you got during registration with alpha-vantage.
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Execute the Python script&lt;/b&gt;:&lt;br /&gt;
Lets run the program, to begin with you can just have one or two stocks in the config file.&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ python alpha_data.py
Fetching for the stock NSE:ADANIPORTS
Completed for the stock NSE:ADANIPORTS in /home/guru/history/stock/adaniports.csv
Fetching for the stock NSE:ASIANPAINT
Completed for the stock NSE:ASIANPAINT in /home/guru/history/stock/asianpaint.csv
Fetching for the stock NSE:AXISBANK
Completed for the stock NSE:AXISBANK in /home/guru/history/stock/axisbank.csv
$
&lt;/pre&gt;
Checking the content of one of the feed files:&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ head -3 /home/guru/history/stock/axisbank.csv
Date,Open,High,Low,Close,Volume
2000-01-03,5.4394,5.4527,5.3779,5.4,521349.0
2000-01-04,5.4,5.51,5.08,5.38,494000.0
$ 
$ tail -3 /home/guru/history/stock/axisbank.csv
2020-04-20,482.0,483.45,451.25,455.95,42163627.0
2020-04-21,436.0,439.95,412.95,420.65,33572119.0
2020-04-22,418.55,434.55,412.0,431.15,36619611.0
$ 
&lt;/pre&gt;
Start playing with your data!!!&lt;br /&gt;
&lt;br /&gt;
&amp;nbsp;Note:&amp;nbsp; A sleep of 20 seconds is given because alpha vantage allows only 3 API calls per minute.
</description><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">1</thr:total><author>guru@theunixschool.com (Guru Prasad)</author></item><item><title>Python - Get nth prime number</title><link>http://www.theunixschool.com/2020/04/python-get-nth-prime-number.html</link><category>eulers project</category><category>iterators</category><category>prime numbers</category><category>python</category><category>python3</category><pubDate>Sat, 11 Apr 2020 16:02:00 +0530</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-1255024703457423340.post-8996115137799426338</guid><description>&amp;nbsp;Let us try to solve the &lt;a href="https://projecteuler.net/problem=7"&gt;7th problem in Euler's project&lt;/a&gt; which is to get the 10,001st prime number. We will start with writing a function to check if a number is prime or not.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="gpr1"&gt;from math import sqrt

def isPrime(x):
    if x &amp;lt; 2:
        return False
    if x == 2 or x == 3:
        return True
    for i in range(2, int(sqrt(x)) + 1):
        if x % i == 0:
            return False

    return True
&lt;/pre&gt;
&lt;a name='more'&gt;&lt;/a&gt;Let us try this in Repl:&lt;br /&gt;
&lt;pre class="gpr1"&gt;&amp;gt;&amp;gt;&amp;gt; isPrime(6)
False
&amp;gt;&amp;gt;&amp;gt; isPrime(13)
True
&amp;gt;&amp;gt;&amp;gt; 
&lt;/pre&gt;
&amp;nbsp; Now we will write a function to get the nth prime, i.e,&amp;nbsp; if n is 3, we should get 5 which is the 3rd prime number.&lt;br /&gt;
&lt;pre class="gpr1"&gt;def getNthPrime(x):
    cnt = 0
    num = 2
    while True:
        if isPrime(num):
            cnt = cnt + 1
            if cnt == x:
                return num
        num = num + 1
&lt;/pre&gt;
Testing in REPL:&lt;br /&gt;
&lt;pre class="gpr1"&gt;&amp;gt;&amp;gt;&amp;gt; getNthPrime(3)
5
&amp;gt;&amp;gt;&amp;gt; getNthPrime(5)
11
&lt;/pre&gt;
&amp;nbsp; Similarly to get the 10,001st prime number:&lt;br /&gt;
&lt;pre class="gpr1"&gt;&amp;gt;&amp;gt;&amp;gt; getNthPrime(10001)
104743
&amp;gt;&amp;gt;&amp;gt;
&lt;/pre&gt;
&amp;nbsp;Lets find out the time elapsed to get this:&lt;br /&gt;
&lt;pre class="gpr1"&gt;&amp;gt;&amp;gt;&amp;gt; from timeit import timeit
&amp;gt;&amp;gt;&amp;gt; 
&amp;gt;&amp;gt;&amp;gt; timeit('getNthPrime(10001)', globals=globals(), number = 1)
0.289607039999737
&amp;gt;&amp;gt;&amp;gt; 
&lt;/pre&gt;
&amp;nbsp; &amp;nbsp;All it took is just a quarter of a second to get the 10,001st prime.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Using itertools&lt;/b&gt;:&lt;br /&gt;
&amp;nbsp; &amp;nbsp; &lt;i&gt;getNthPrime&lt;/i&gt; function can be completely avoided by using itertools. &lt;i&gt;itertools&lt;/i&gt; has 2 important functions:&lt;br /&gt;
&amp;nbsp; &lt;i&gt;islice&lt;/i&gt; - returns an iterator of a slice of values&lt;br /&gt;
&amp;nbsp; &lt;i&gt;count&lt;/i&gt; - returns an iterator of values. Similar to range function, but it does not take the end value.&lt;br /&gt;
&amp;gt;&amp;gt;&amp;gt; islice((x for x in count() if isPrime(x)),10001)&lt;br /&gt;
&lt;pre class="gpr1"&gt;&amp;lt;itertools.islice object at 0x7fbc350ab8b8&amp;gt;
&amp;gt;&amp;gt;&amp;gt; 
&amp;gt;&amp;gt;&amp;gt; list(islice((x for x in count() if isPrime(x)),10001))[-1]
104743
&amp;gt;&amp;gt;&amp;gt; 
&lt;/pre&gt;
&amp;nbsp;Using the count we get an iteration of infinite list of numbers and only the prime ones are filtered. &lt;i&gt;islice&lt;/i&gt; takes the 1st 10,001 numbers and stops the iteration.&lt;br /&gt;
&amp;nbsp; &amp;nbsp;The result is taken in &lt;i&gt;list&lt;/i&gt; context and we print the last element which is the 10,0001st prime.&lt;br /&gt;
&lt;pre class="gpr1"&gt;&amp;gt;&amp;gt;&amp;gt; timeit('list(islice((x for x in count() if isPrime(x)),10001))[-1]', globals = globals(), number = 1)
0.3422034679997523
&amp;gt;&amp;gt;&amp;gt; 
&lt;/pre&gt;
&amp;nbsp; Time taken is almost same as what it took in the earlier one.</description><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><author>guru@theunixschool.com (Guru Prasad)</author></item><item><title>Perl - Connect to Oracle database and SELECT </title><link>http://www.theunixschool.com/2017/07/perl-connect-to-oracle-database-and.html</link><category>database</category><category>Oracle</category><category>Perl</category><pubDate>Tue, 25 Jul 2017 10:19:00 +0530</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-1255024703457423340.post-8800734794014944232</guid><description>&lt;div&gt;
&lt;div&gt;
How to connect to a database from a Perl program? Let us see in this article how to connect to Oracle and read from a table. &amp;nbsp;As a pre-requisite, we need to have the &lt;i&gt;DBI&lt;/i&gt; and &lt;i&gt;DBD::Oracle&lt;/i&gt; packages installed. &lt;br /&gt;
&amp;nbsp; &amp;nbsp;In this article, we are going to see how to read name of a student from the students table.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Example 1&lt;/b&gt;:&lt;/div&gt;
&lt;/div&gt;
&lt;pre class="gpr1"&gt;#!/usr/bin/perl 
use warnings ;
use strict ;
use DBI;

$\="\n";

print "Connecting to DB..";

my $dbh = DBI-&amp;gt;connect('dbi:Oracle:xe',  'scott', 'tiger') or
          die "Cannot connect to DB =&amp;gt; " . DBI-&amp;gt;errstr;
my $sth = $dbh-&amp;gt;prepare("select first_name, last_name from students where id = 10000") or
          die "Couldn't prepare statement: " . $dbh-&amp;gt;errstr;
$sth-&amp;gt;execute();

while (my ($f_name, $l_name) = $sth-&amp;gt;fetchrow_array()){
    printf "First Name : %-10s Last Name : %-20s\n" , $f_name,  $l_name;
}
#$sth-&amp;gt;finish();
$dbh-&amp;gt;disconnect();

&lt;/pre&gt;
&lt;br /&gt;
The above program when run will print the First Name and last name of the student whose id is 10000.&lt;br /&gt;
&lt;br /&gt;
&lt;a name='more'&gt;&lt;/a&gt;&lt;br /&gt;
1. &amp;nbsp;DBI-&amp;gt;connect &amp;nbsp;=&amp;gt; This is to connect to the Oracle database, where 'xe' is the name of the database, 'scott' is the username, and 'tiger' is the password. &amp;nbsp;This function returns a database handler object.&lt;br /&gt;
&lt;br /&gt;
2. $dbh-&amp;gt;prepare =&amp;gt; This command prepares a query provided and creates a statement handler object.&lt;br /&gt;
&lt;br /&gt;
3. $sth-&amp;gt;execute() =&amp;gt; This will submit the query to Oracle and gets it executed. Keep in mind, this just executes the query, does not return the result back though.&lt;br /&gt;
&lt;br /&gt;
4. $sth-&amp;gt;fetchrow_array() =&amp;gt; This is the one which fetches the result of the last query executed. &amp;nbsp;A while loop is used to parse this result just in case the output returns multiple rows, still it can be handled. &lt;br /&gt;
&amp;nbsp; &amp;nbsp;In this case, since the query returns 2 columns, we are collecting it in 2 variables and then printing the values.&lt;br /&gt;
&lt;br /&gt;
5. $sth-&amp;gt;finish =&amp;gt; This tells Oracle that we are done with fetching the results for the query. If we are reading all the results of the query, then this should not be given. It is needed only in cases when we are reading partial results.&lt;br /&gt;
&lt;br /&gt;
6. $dbh-&amp;gt;disconnect =&amp;gt; This disconnects the connection with the Oracle. Any subsequent query if needs to be executed, we should connect again. Usually, this is done at the end of the program.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Example 2&lt;/b&gt;:&lt;br /&gt;
&amp;nbsp; &amp;nbsp;In this, the query is parameterized where the parameter is passed as part of the execute command:&lt;br /&gt;
&lt;pre class="gpr1"&gt;#!/usr/bin/perl 
use warnings ;
use strict ;
use DBI;

$\="\n";

print "Connecting to DB..";

my $dbh = DBI-&amp;gt;connect('dbi:Oracle:xe',  'scott', 'tiger') or
          die "Cannot connect to DB =&amp;gt; " . DBI-&amp;gt;errstr;
my $sth = $dbh-&amp;gt;prepare("select first_name, last_name from students where id = ?") or
          die "Couldn't prepare statement: " . $dbh-&amp;gt;errstr;
$sth-&amp;gt;execute("10000");

while (my ($f_name, $l_name) = $sth-&amp;gt;fetchrow_array()){
    printf "First Name : %-10s Last Name : %-20s\n" , $f_name,  $l_name;
}
$sth-&amp;gt;finish();
$dbh-&amp;gt;disconnect();
&lt;/pre&gt;
&lt;div&gt;
&lt;div&gt;
&lt;br class="Apple-interchange-newline" /&gt;
&lt;b&gt;Example 3&lt;/b&gt;:&lt;br /&gt;
&amp;nbsp; &amp;nbsp; In this, instead of collecting the result in 2 scalar variables, it is being assigned to an array, and then we are accessing using the array index positions.&lt;/div&gt;
&lt;pre class="gpr1"&gt;my @data=();
while (@data = $sth-&amp;gt;fetchrow_array()){
    printf "First Name : %-10s Last Name : %-20s\n" , $data[0], $data[1];
}
&lt;/pre&gt;
&lt;/div&gt;
</description><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><author>guru@theunixschool.com (Guru Prasad)</author></item><item><title>grep vs awk - Part 2</title><link>http://www.theunixschool.com/2017/01/grep-vs-awk-part-2.html</link><category>awk</category><category>awk pattern matching</category><category>grep command</category><pubDate>Wed, 11 Jan 2017 11:28:00 +0530</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-1255024703457423340.post-7568283897640781908</guid><description>In this article, we will see more awk alternatives for the frequently used grep commands. This is in continuation to the &lt;a href="http://www.theunixschool.com/2012/09/grep-vs-awk-examples-for-pattern-search.html"&gt;grep vs awk - Part 1&lt;/a&gt;.
Let us consider a sample file as shown below:
&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ cat file
Unix

Linux
Uniix
Solaris
AIX
ArchLinux
Ubuntu
&lt;/pre&gt;
&lt;b&gt;1. Search for a pattern present in a variable
&lt;/b&gt;&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ x="Linux"
$ grep "$x" file
Linux
&lt;/pre&gt;
The variable x contains the search pattern. Using grep, the variable can directly be used.
&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ awk -v var="$x" '$0 ~ var' file
Linux
&lt;/pre&gt;
In awk, the variable cannot be used directly. It needs to be passed to awk from shell using the -v option. More about the &lt;a href="http://www.theunixschool.com/2011/09/awk-passing-arguments-or-shell.html"&gt;variable passing to awk&lt;/a&gt;.
&lt;br /&gt;
&lt;a name='more'&gt;&lt;/a&gt;&lt;b&gt;&lt;br /&gt;&lt;/b&gt;
&lt;b&gt;2. Search for lines beginning with a specific pattern:
&lt;/b&gt;&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ grep '^S' file
Solaris
&lt;/pre&gt;
The ^ symbol is used to search for lines which begin with. In this example, we are trying to search for lines which are beginning with is S.
&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ awk '/^S/' file
Solaris
&lt;/pre&gt;
&lt;b&gt;3. Search for&amp;nbsp;&lt;/b&gt;&lt;b&gt;lines&lt;/b&gt;&lt;b&gt;&amp;nbsp;ending with a specific pattern:
&lt;/b&gt;&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ grep 'x$' file
Unix
Uniix
Linux
ArchLinux
&lt;/pre&gt;
The $ symbol is used to search for matches which are ending with.
&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ awk '/x$/' file
Unix
Uniix
Linux
ArchLinux
&lt;/pre&gt;
&lt;b&gt;4. To search for a exact word in a file:
&lt;/b&gt;&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ grep -w Linux file
Linux
&lt;/pre&gt;
The option -w is used in grep for the specific word search. The pattern ArchLinux did not retutrn because 'Linux' is just part of the the word.
&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ awk '{for(i=1;i&amp;lt;=NF;i++)if($i=="Linux"){print;}}' file
Linux
&lt;/pre&gt;
In awk, we need to loop over the columns and compare &amp;nbsp;the value against every column.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;5. To get count of lines matching pattern:
&lt;/b&gt;&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ grep -c ix file
2
&lt;/pre&gt;
The -c option of grep gives the count of lines matching the pattern. The "ix" pattern is matched in 2 lines.
&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ awk '/ix/{x++}END{print x}' file
2
&lt;/pre&gt;
In awk, whenever the pattern "ix" is matched, a variable x is incremented. At the end of the file processing, x contains the count of lines matching the pattern.
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;6. Search for a pattern which exactly matches the whole line:
&lt;/b&gt;&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ grep -x Linux file
Linux
&lt;/pre&gt;
grep has the -x option for matching exact matches.
&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ awk '/^Linux$/' file
Linux
&lt;/pre&gt;
In awk, we use the ^ (beginning with) and $(ending with) meta characters to search for the exact match.
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;7. Search for non-empty lines or lines containing atleast one character:
&lt;/b&gt;&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ grep . file
Unix
Linux
Uniix
Solaris
AIX
ArchLinux
Ubuntu
&lt;/pre&gt;
The . matches any character. Since empty line does not have any, it does not match.
&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ awk NF file
Unix
Linux
Uniix
Solaris
AIX
ArchLinux
Ubuntu
&lt;/pre&gt;
NF indicates number of fields. Since an empty line will have NF as 0, it does not get matched.
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;8. Extract part of the line instead of the entire line:
&lt;/b&gt;&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ grep -o "..$" file
ix
ux
ix
is
IX
tu
&lt;/pre&gt;
By default, grep prints the entire line which matches the pattern. Using -o option only a part of string can be extracted. .. extracts 2 characters, ..$ extracts 2 characters from the end of the line.
&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ awk 'NF{print substr($0,length-1);}' file
ix
ux
ix
is
IX
tu
&lt;/pre&gt;
awk uses the sub-string function(substr) to do the extraction.
&lt;br /&gt;
&lt;br /&gt;
Let us consider another sample file with 2 columns in it:
&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ cat file
Unix 2
Linux 3
Uniix 4
Solaris 5
&lt;/pre&gt;
&lt;b&gt;9. Extract the 2nd column from the lines containing a specific pattern :
&lt;/b&gt;&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ grep Uni file | cut -d" " -f2
2
4
&lt;/pre&gt;
grep extracts the lines containing the pattern, and cut extracts only the 2nd column.
&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ awk '/Uni/{print $2}' file
2
4
&lt;/pre&gt;
In awk, searching a pattern and printing a particular column all are done as part of the same command.
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;10. Extracting first 3 characters from lines containing a specific pattern:
&lt;/b&gt;&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ grep x file | cut -c 1-3
Uni
Lin
Uni
&lt;/pre&gt;
grep extracts lines containing the pattern 'x' and cut cuts the 1st three columns.
&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ awk '/x/{print substr($0,1,3)}' file
Uni
Lin
Uni
&lt;/pre&gt;
&lt;br /&gt;
To know&amp;amp; learn &amp;nbsp;more about the &lt;i&gt;awk&lt;/i&gt;, you can refer to the &lt;a href="http://www.theunixschool.com/p/awk-sed.html"&gt;awk related articles&lt;/a&gt;.</description><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><author>guru@theunixschool.com (Guru Prasad)</author></item><item><title>How to use arrays in ksh?</title><link>http://www.theunixschool.com/2017/01/how-to-use-arrays-in-ksh.html</link><category>array</category><category>ksh arrays examples</category><pubDate>Wed, 4 Jan 2017 12:16:00 +0530</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-1255024703457423340.post-3176032967862596686</guid><description>&amp;nbsp; Array, as in any programming language, is a collection of elements. These elements need not be of the same type. One important difference here is shells support only one-dimensional arrays.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;1. Creating an array&lt;/b&gt;:&lt;br /&gt;
&amp;nbsp; &amp;nbsp;Creating an array is pretty simple.&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ typeset -a arr
$ arr[0]=25
$ arr[1]=18
$ arr[2]="hello"&lt;/pre&gt;
&amp;nbsp;Using the typeset command, we let the shell know that we are intending to use the variable &lt;i&gt;arr&lt;/i&gt; to store a list of elements. The &lt;i&gt;-a&lt;/i&gt; indicates arr as an indexed array. Then the elements are assigned one by one using their index positions. Array indexing always starts from 0.&lt;br /&gt;
&lt;a name='more'&gt;&lt;/a&gt;&lt;br /&gt;
To print the 1st element of the array:&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ echo ${arr[0]}
25&lt;/pre&gt;
Similarly, to print the 2nd element of the array:&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ echo ${arr[1]}
18&lt;/pre&gt;
To get the total number of elements in the array:&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ echo ${#arr[*]}&amp;nbsp;
3&lt;/pre&gt;
To print all the elements of the array:&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ echo ${arr[*]}
25 18 hello
&lt;/pre&gt;
&amp;nbsp; OR
&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ echo ${arr[@]}
25 18 hello
&lt;/pre&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
&amp;nbsp; The difference between using the * and&amp;nbsp;@ is same as the &lt;a href="http://www.theunixschool.com/2011/03/difference-between-and-in-shell.html"&gt;difference between using $* and $@ &lt;/a&gt;in case of command line arguments.&lt;/div&gt;
&lt;br /&gt;
&lt;b&gt;Declaring an initializing an array at one go&lt;/b&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ typeset -a arr=(25 18 &amp;nbsp;"hello")
&lt;/pre&gt;
&amp;nbsp; OR
&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ typeset -a arr
$ arr=(25 18 &amp;nbsp;"hello")
&lt;/pre&gt;
&amp;nbsp; &amp;nbsp;Array is initialized by having values inside brackets. Every element within the brackets are assigned to individual index positions.&lt;br /&gt;
&lt;b&gt;Accessing the array elements one by one using a for loop&lt;/b&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;for i in ${arr[*]}
do
&amp;nbsp; &amp;nbsp; echo $i
done&lt;/pre&gt;
Similarly, we can access the array elements using for loop by using&amp;nbsp;@ instead of *:&lt;br /&gt;
&lt;pre class="gpr1"&gt;for i in "${arr[@]}"
do
&amp;nbsp; &amp;nbsp; echo $i
done&lt;/pre&gt;
&lt;b&gt;Printing array elements using the printf :&lt;/b&gt;&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ printf "%s\n" ${arr[*]}
25
18
hello
&lt;/pre&gt;
&lt;b&gt;Using array to store contents of a file&lt;/b&gt;&lt;br /&gt;
Let us create a file as shown below:
&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ cat file
Linux
Solaris
Unix
&lt;/pre&gt;
Dumping the file contents to an array:   
&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ arr=($(cat file))
&lt;/pre&gt;
With this, every line of the file gets stored in every index position of the array. Meaning, the 1st line of the file will be in arr[0], 2nd line in arr[1] and so on.&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ echo ${arr[0]}
Linux
&lt;/pre&gt;
&amp;nbsp; Similarly, to print the entire file contents:&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ echo ${arr[*]}
Linux Solaris Unix
&lt;/pre&gt;
&amp;nbsp; Getting the total element count of the array in this case gives the line count of the file:&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ echo ${#arr[*]}
3
&lt;/pre&gt;
</description><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><author>guru@theunixschool.com (Guru Prasad)</author></item><item><title>Perl : Find files using File::Find</title><link>http://www.theunixschool.com/2014/09/perl-find-files-using-filefind.html</link><category>find</category><category>find2perl</category><category>perl file find</category><category>perl find files</category><category>unix find</category><pubDate>Wed, 17 Sep 2014 23:14:00 +0530</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-1255024703457423340.post-7710471009108849196</guid><description>&lt;span style="font-size: x-large;"&gt;H&lt;/span&gt;ow to find the list of files in Perl &amp;nbsp;like the UNIX find command? The answer is&amp;nbsp;&lt;a href="http://search.cpan.org/~rjbs/perl-5.16.3/lib/File/Find.pm"&gt;File::Find&lt;/a&gt;&amp;nbsp;CPAN module. Let us see in this article how to use the File::Find module.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;File::Find&lt;/b&gt;:&lt;br /&gt;
&amp;nbsp; &amp;nbsp;File::Find module contains 2 modules: find and finddepth. Both are used to find the files, the difference being the order in which the files and directories are parsed. find has all the options like the Unix &lt;a href="http://www.theunixschool.com/2012/04/find-files-by-name-or-part-of-name-or.html"&gt;find command&lt;/a&gt;.&lt;br /&gt;
&lt;a name='more'&gt;&lt;/a&gt;&lt;br /&gt;
&lt;b&gt;1. Find all .txt files&lt;/b&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;use File::Find;

my @files;
my @dirpath=qw(/home/user1/);
find(sub {
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;push @files,$File::Find::name if (-f $File::Find::name and /\.txt$/);
&amp;nbsp; &amp;nbsp; &amp;nbsp; }, @dirpath);

print join "\n",@files;
&lt;/pre&gt;
find function takes 2 arguments:&lt;br /&gt;
1. The first argument is a subroutine which is called for each and every file found by the find function.&lt;br /&gt;
2. The 2nd argument is list of directories where the find function will search for files.&lt;br /&gt;
&lt;br /&gt;
By default, the find function searches for all files and directories which in Unix find command can be written as:&lt;br /&gt;
&lt;pre class="gpr1"&gt;find .
&lt;/pre&gt;
&amp;nbsp;Every file found by the find command is pushed into the array&amp;nbsp;@files if it is a file (-f) and has .txt extension(\.txt$). The variable $File::Find::name contains the complete path name of the file.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;2. Find all .txt or .xml files&lt;/b&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;my @files;
my @dirpath=qw(/home/user1/);
find(sub {
&amp;nbsp; &amp;nbsp; &amp;nbsp; push @files,$File::Find::name if (-f $File::Find::name and /\.(txt|xml)$/);
&amp;nbsp; &amp;nbsp; }, @dirpath);

print join "\n",@files;&lt;/pre&gt;
&amp;nbsp;The regex used here checks for either a txt file or a xml file.&lt;br /&gt;
The Unix equivalent of this is:&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ find /home/user1 \( -name "*.txt" -o -name "*.xml" \)&lt;/pre&gt;
&lt;b&gt;3&lt;/b&gt;.&amp;nbsp;&lt;b&gt;Find all dirs&lt;/b&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;use File::Find;

my @files;
my @dirpath=qw(/home/user1);
find(sub {
&amp;nbsp; &amp;nbsp; &amp;nbsp;  &amp;nbsp;push @files,$File::Find::name if (-d $File::Find::name );
&amp;nbsp; &amp;nbsp; &amp;nbsp; }, @dirpath);

print join "\n",@files;&lt;/pre&gt;
&amp;nbsp; The directories alone are filtered by checking for the -d option against the $File::Find::name variable.&lt;br /&gt;
The Unix equivalent of this is:&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ find /home/user1 -type d&lt;/pre&gt;
&lt;b&gt;4. Files modified in the last 1 day&lt;/b&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;use File::Find;

my @files;
my @dirpath=qw(/home/user1/);
find(sub {
&amp;nbsp; &amp;nbsp; &amp;nbsp; push @files,$File::Find::name if (-f $File::Find::name and int(-M $_) &amp;lt; 1);
&amp;nbsp; &amp;nbsp; }, @dirpath);

print join "\n",@files;&lt;/pre&gt;
-M filename gives the age of the file which is nothing but the number of days since it is last modified. By checking this value to be less than 1, files modified in the last day can be retrieved.&lt;br /&gt;
&lt;br /&gt;
The Unix equivalent of this is:&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ find /home/user1 -mtime -1&lt;/pre&gt;
&lt;b&gt;5. Files modified in the last 1 hour&lt;/b&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;my @files;
my @dirpath=qw(/home/user1/);
find(sub {
&amp;nbsp; &amp;nbsp; &amp;nbsp; push @files,$File::Find::name if (-f $File::Find::name and (-M $_) &amp;lt; 1/24);
&amp;nbsp; &amp;nbsp; }, @dirpath);

print join "\n",@files;
&lt;/pre&gt;
Since -M gives the number of days since the file is last modified, by checking it against 1/24 filters only those files whose age is less than 1 hour.&lt;br /&gt;
&lt;br /&gt;
The Unix equivalent of this is:&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ find /home/user1 -mmin -60&lt;/pre&gt;
&lt;b&gt;6. Files modified in the last 30 mins&lt;/b&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;my @files;
my @dirpath=qw(/home/user1/);
find(sub {
 &amp;nbsp; &amp;nbsp;push @files,$File::Find::name if (-f $File::Find::name and (-M $_) &amp;lt; 0.5/24); &amp;nbsp; }, @dirpath);

print join "\n",@files;&lt;/pre&gt;
The Unix equivalent of this is:&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ find /home/user1 -mmin -30&lt;/pre&gt;
This module, along with the functions, provides some variables as well. The following are those:&lt;br /&gt;
$name : the full name of the file&lt;br /&gt;
$dir : contains the name of the current directory in which &lt;i&gt;find&lt;/i&gt; is finding.&lt;br /&gt;
&lt;br /&gt;
Note: The &lt;a href="http://www.theunixschool.com/2012/07/find2perl-10-examples-to-find-files.html"&gt;find2perl&lt;/a&gt; command internally uses the File::Find module itself.</description><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><author>guru@theunixschool.com (Guru Prasad)</author></item><item><title>sed - 20 examples to remove / delete characters from a file</title><link>http://www.theunixschool.com/2014/08/sed-examples-remove-delete-chars-from-line-file.html</link><category>delete character</category><category>sed</category><category>sed regular expression</category><category>sed replace</category><pubDate>Wed, 13 Aug 2014 23:25:00 +0530</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-1255024703457423340.post-4491733866265148704</guid><description>In this article of &lt;a href="http://www.theunixschool.com/p/awk-sed.html"&gt;sed series&lt;/a&gt;, we will see the examples of how to remove or delete characters from a file. The syntax of sed command replacement is:&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ sed 's/find/replace/' file
&lt;/pre&gt;
&amp;nbsp;This sed command finds the pattern and replaces with another pattern. When the replace is left empty, the pattern/element found gets deleted.&lt;br /&gt;
&lt;br /&gt;
Let us consider a sample file as below:&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ cat file
Linux
Solaris
Ubuntu
Fedora
RedHat
&lt;/pre&gt;

&lt;a name='more'&gt;&lt;/a&gt;
&lt;b&gt;1&lt;/b&gt;. &lt;b&gt;To remove a specific character&lt;/b&gt;, say 'a'
&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ sed 's/a//' file
Linux
Solris
Ubuntu
Fedor
RedHt
&lt;/pre&gt;
&amp;nbsp; This will remove the first occurence of 'a' in every line of the file. To remove all occurences of 'a' in every line,&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ sed 's/a//g' file
&lt;/pre&gt;
&lt;b&gt;2&lt;/b&gt;. &lt;b&gt;To remove 1st character in every line&lt;/b&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ sed 's/^.//' file
inux
olaris
buntu
edora
edHat
&lt;/pre&gt;
&amp;nbsp; .(dot) tries to match a single character. The &amp;nbsp;^ tries to match a pattern(any character) in the beginning of the line. &amp;nbsp; Another way to write the same:&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ sed 's/.//' file
&lt;/pre&gt;
&amp;nbsp; This tells to replace a character with nothing. Since by default, sed starts from beginning, it replaces only the 1st character since 'g' is not passed.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;3. To remove last character of every line&lt;/b&gt; :
&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ sed 's/.$//' file
Linu
Solari
Ubunt
Fedor
RedHa
&lt;/pre&gt;
&amp;nbsp; The $ tries to match a pattern in the end of the line.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;4. To remove the 1st and last character of every line in the same command&lt;/b&gt;:
&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ sed 's/.//;s/.$//' file
inu
olari
bunt
edor
edHa
&lt;/pre&gt;
&amp;nbsp; &amp;nbsp;Two commands can be given together with a semi-colon separated in between.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;5. To remove first character only if it is a specific character&lt;/b&gt;:
&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ sed 's/^F//' file
Linux
Solaris
Ubuntu
edora
RedHat
&lt;/pre&gt;
&amp;nbsp; This removes the 1st character only if it is 'F'.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;6. To remove last character only if it is a specific character&lt;/b&gt;:
&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ sed 's/x$//' file
Linu
Solaris
Ubuntu
Fedora
RedHat
&lt;/pre&gt;
&amp;nbsp; &amp;nbsp;This removed the last character only if it s 'x'.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;7. To remove 1st 3 characters of every line&lt;/b&gt;:
&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ sed 's/...//' file
ux
aris
ntu
ora
Hat
&lt;/pre&gt;
&amp;nbsp; A single dot(.) removes 1st character, 3 dots remove 1st three characters.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;8. To remove 1st n characters of every line&lt;/b&gt;:
&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ sed -r 's/.{4}//' file
x
ris
tu
ra
at
&lt;/pre&gt;
&amp;nbsp; &amp;nbsp;.{n} -&amp;gt; matches any character n times, and hence the above expression matches 4 characters and deletes it.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;9. To remove last n characters of every line&lt;/b&gt;:
&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ sed -r 's/.{3}$//' file
Li
Sola
Ubu
Fed
Red
&lt;/pre&gt;
&amp;nbsp; &lt;br /&gt;
&lt;b&gt;10. To remove everything except the 1st n characters in every line&lt;/b&gt;:
&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ sed -r 's/(.{3}).*/\1/' file
Lin
Sol
Ubu
Fed
Red
&lt;/pre&gt;
&amp;nbsp; .* -&amp;gt; matches any number of characters, and the first 3 characters matched are grouped using parantheses. In the replacement, by having \1 only the group is retained, leaving out the remaining part.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;11. To remove everything except the last n characters in a file&lt;/b&gt;:
&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ sed -r 's/.*(.{3})/\1/' file
nux
ris
ntu
ora
Hat
&lt;/pre&gt;
&amp;nbsp; Same as last example, except that from the end.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;12. To remove multiple characters present in a file&lt;/b&gt;:
&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ sed 's/[aoe]//g' file
Linux
Slris
Ubuntu
Fdr
RdHt
&lt;/pre&gt;
&amp;nbsp; &amp;nbsp;To delete multiple characters, [] is used by specifying the characters to be removed. This will remove all occurences of the characters a, o and e.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;13. To remove a pattern &amp;nbsp;&lt;/b&gt;:
&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ sed 's/lari//g' file
Linux
Sos
Ubuntu
Fedora
RedHat
&lt;/pre&gt;
&amp;nbsp;Not just a character, even a pattern can be removed. Here, 'lari' got removed from 'Solaris'.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;14. To delete only nth occurrence of a character in every line&lt;/b&gt;:
&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ sed 's/u//2' file
Linux
Solaris
Ubunt
Fedora
RedHat
&lt;/pre&gt;
&amp;nbsp; By default, sed performs an activity only on the 1st occurence. If n is specifed, sed performs only on the nth occurence of the pattern. The 2nd 'u' of 'Ubuntu' got deleted.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;15. To delete everything in a line followed by a character&lt;/b&gt;:
&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ sed 's/a.*//' file
Linux
Sol
Ubuntu
Fedor
RedH
&lt;/pre&gt;
&lt;br /&gt;
&lt;b&gt;16. To remove all digits present in every line of a file&lt;/b&gt;:
&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ sed 's/[0-9]//g' file
&lt;/pre&gt;
&amp;nbsp; [0-9] stands for all characters between 0 to 9 meaning all digits, and hence all digits get removed.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;17. To remove all lower case alphabets present in every line&lt;/b&gt;:
&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ sed 's/[a-z]//g' file
L
S
U
F
RH
&lt;/pre&gt;
&amp;nbsp; [a-z] represents lower case alphabets range and hence all lower-case characters get removed.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;18. To remove everything other than the lower case alphabets&lt;/b&gt;:
&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ sed 's/[^a-z]//g' file
inux
olaris
buntu
edora
edat
&lt;/pre&gt;
&amp;nbsp; &amp;nbsp;^ inside square brackets negates the condition. Here, all characters except lower case alphabets get removed.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;19. To remove all alpha-numeric characters present in every line&lt;/b&gt;:
&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ sed 's/[a-zA-Z0-9]//g' file
&lt;/pre&gt;
&amp;nbsp; &amp;nbsp; All alpha-numeric characters get removed.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;20. To remove a character irrespective of the case&lt;/b&gt;:
&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ sed 's/[uU]//g' file
Linx
Solaris
bnt
Fedora
RedHat
&lt;/pre&gt;
&amp;nbsp;By specifying both the lower and upper case character in brackets is equivalent to removing a character irrespective of the case.</description><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">22</thr:total><author>guru@theunixschool.com (Guru Prasad)</author></item><item><title>How to use SUID for shell scripts in Linux?</title><link>http://www.theunixschool.com/2013/11/how-to-use-suid-for-shell-scripts-in.html</link><category>linux</category><category>Oracle</category><category>shell script</category><category>sqlplus</category><category>SUID</category><pubDate>Tue, 12 Nov 2013 10:25:00 +0530</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-1255024703457423340.post-176475834387962960</guid><description>Question : How to write a shell script which will read the required passwords/connect strings from a config file? Other users should be able to execute the scripts, however they should not be able to read the config file.&lt;br /&gt;
&lt;br /&gt;
Say, I have a config file, myconfig.txt, which contains credentials for an oracle connection:&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ cat myconfig.txt
SQLUSR="scott"
SQLPWD="pwd123"&lt;/pre&gt;
&lt;a name='more'&gt;&lt;/a&gt;Shell script,script1.sh, to connect to Oracle and get employee name:&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ cat script1.sh
#!/usr/bin/bash

source myconfig.txt

NM=`sqlplus -s ${SQLUSR}/${SQLPWD}@XE &amp;lt;&amp;lt;EOF
set heading off
select ename from emp where empno=7369;
EOF`

echo Name is $NM&lt;/pre&gt;
The issue here is: Any user, who has permissions to run this script can get to know the password present in the myconfig.txt either by reading the file directly or by running the shell script in debug mode.&lt;br /&gt;
&lt;br /&gt;
How to prevent the user from reading the password?&lt;br /&gt;
&amp;nbsp; &amp;nbsp;By removing the read permission from the group and others on the myconfig.txt file will not help. Because, in that case, the other users will not be able to run the script as well.&lt;br /&gt;
&lt;br /&gt;
Setting the &lt;a href="http://www.theunixschool.com/2010/06/what-is-suid.html"&gt;SUID&lt;/a&gt; on the Shell script:&lt;br /&gt;
&amp;nbsp; &amp;nbsp; After removing the read permission and then applying the suid bit on the shell script will work on say Solaris, will not work in Linux flavors. Because &lt;a href="http://www.theunixschool.com/2010/06/what-is-suid.html"&gt;SUID&lt;/a&gt; can be applied only on binary executables in Linux.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Solution&lt;/b&gt;:&lt;br /&gt;
&amp;nbsp; &amp;nbsp;In order to create a binary executable, we need to write our code in either say C, C++, etc..which gives binary executables.&lt;br /&gt;
&amp;nbsp; &amp;nbsp;Let us write a C program which reads the myconfig.txt file and sets environment variables for all the entries present in the file. And then invoking the shell script from the C program should suffice:&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ cat getName.c
#include&amp;lt;stdio.h&amp;gt;
#include&amp;lt;string.h&amp;gt;
#include&amp;lt;stdlib.h&amp;gt;

int main()
{
&amp;nbsp; &amp;nbsp; FILE *fp = fopen("/home/guru/C/myconfig.txt","r");
&amp;nbsp; &amp;nbsp; char data[128];
&amp;nbsp; &amp;nbsp; char *d1;
&amp;nbsp; &amp;nbsp; while(fgets(data,128,fp)!=NULL){
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; d1=(char *)malloc(128);
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; strcpy(d1,data);
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; d1[strlen(d1)-1]='\0';
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; putenv(d1);
&amp;nbsp; &amp;nbsp; }
&amp;nbsp; &amp;nbsp; fclose(fp);
&amp;nbsp; &amp;nbsp; system("/home/guru/C/script.sh");
}&lt;/pre&gt;
&amp;nbsp;Creating an executable for this C program :&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ gcc -o getName getName.c
$ ./getName
NM is SMITH&lt;/pre&gt;
Remove the read permission on the myconfig.txt file for group and others and applying the SUID on the executable:&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ chmod go-r myconfig.txt
$ chmod u+s getName&lt;/pre&gt;
Logging as a different user to check :&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ su - guest
$ echo $USER
guest
$ cd /home/guru/C
$ ./getName
NM is SMITH
$ cat myconfig.txt
cat: myconfig.txt: Permission denied
&lt;/pre&gt;
&amp;nbsp; On applying the SUID permission, the other user when trying to execute the script, gets the same permission as the owner on the myconfig.txt file and hence the script is able to read the file.</description><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">2</thr:total><author>guru@theunixschool.com (Guru Prasad)</author></item><item><title>Python - How to write a list to a file?</title><link>http://www.theunixschool.com/2013/08/python-how-to-write-list-to-file.html</link><category>join method</category><category>python file writing</category><category>python list</category><category>write method</category><category>writelines method</category><pubDate>Tue, 13 Aug 2013 10:36:00 +0530</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-1255024703457423340.post-1425067167085640350</guid><description>How to write an entire list of elements into a file? Let us see in this article how to write a list l1 to a file 'f1.txt':&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;1. Using write method&lt;/b&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;#!/usr/bin/python

l1=['hi','hello','welcome']

f=open('f1.txt','w')
for ele in l1:
    f.write(ele+'\n')

f.close()
&lt;/pre&gt;
&amp;nbsp;The list is iterated, and during every iteration, the &lt;i&gt;write &lt;/i&gt;method writes a line to a file along with the newline character.&lt;br /&gt;
&lt;a name='more'&gt;&lt;/a&gt;&lt;br /&gt;
&lt;b&gt;2. Using string join method&lt;/b&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;#!/usr/bin/python

l1=['hi','hello','welcome']

f=open('f1.txt','w')
s1='\n'.join(l1)
f.write(s1)
f.close()
&lt;/pre&gt;
&amp;nbsp; Using &lt;i&gt;join &lt;/i&gt;method, the entire list can be joined using a delimiter and formed into a string. Now, using the write method, the string can be written to the file. In this, only one write method is needed for the entire list.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;3. Using string join along with &amp;nbsp;&lt;i&gt;with open&lt;/i&gt; syntax&lt;/b&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;#!/usr/bin/python

l1=['hi','hello','welcome']

with open('f1.txt','w') as f:
  f.write('\n'.join(l1))
&lt;/pre&gt;
&amp;nbsp; The &lt;i&gt;with open&lt;/i&gt; syntax automatically closes the file at the end of the block, hence no need of explicit call to the close method. Instead of using a variable to contain the joined string, it is directly given to the write method.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;4. Using the writelines method&lt;/b&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;#!/usr/bin/python

l1=['hi','hello','welcome']

f=open('f1.txt','w')
l1=map(lambda x:x+'\n', l1)
f.writelines(l1)
f.close()
&lt;/pre&gt;
&amp;nbsp;Python provides a method, &lt;i&gt;writelines&lt;/i&gt;, which is very useful to write lists to a file. write method takes a string as argument, &lt;i&gt;writelines&lt;/i&gt; takes a list. &lt;i&gt;writelines &lt;/i&gt;method will write all the elements of the list to a file. Since it writes to the file as is, before invoking the &lt;i&gt;writelines&lt;/i&gt; method, the list elements should be appended with newline characters, so that the list elements will come in individual lines. This is achieved using the &lt;i&gt;map &lt;/i&gt;function which will add a newline to every list element.</description><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">3</thr:total><author>guru@theunixschool.com (Guru Prasad)</author></item><item><title>Python - How to find the location of a module?</title><link>http://www.theunixschool.com/2013/07/python-how-to-find-location-of-module.html</link><category>find module location</category><category>python</category><category>sys module</category><category>sys.path</category><pubDate>Tue, 30 Jul 2013 11:55:00 +0530</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-1255024703457423340.post-4283775167889562003</guid><description>When a module is imported into a program, how to find out the path from where the module is getting picked?&lt;br /&gt;
&lt;br /&gt;
&amp;nbsp; &amp;nbsp; In the Unix world, when a command say ls is executed, the operating system searches in a list of directories for the command executable and once found, executes the command. The list of directories is maintained in the &lt;a href="http://www.theunixschool.com/2010/01/what-is-path-variable.html"&gt;PATH &lt;/a&gt;variable.&lt;br /&gt;
&amp;nbsp; &amp;nbsp; Similarly, in Python, whenever a module is imported, say "import collections', python also searches in a list of directories to find the module file "collections.py", and once found, includes the module. The list of directories to be searched is maintained in a list, sys.path, from the sys module. Hence, this can be accessed using the sys.path.&lt;br /&gt;
&lt;a name='more'&gt;&lt;/a&gt;&lt;br /&gt;
Let us write a script, findmod.py, to find the path of the module 'collections' :&lt;br /&gt;
&lt;pre class="gpr1"&gt;#!/usr/bin/python

import sys,os
from collections import Counter

file_name='collections.py'

for folder in sys.path:
    fname=os.path.join(folder,file_name)
    if os.path.isfile(fname):
       print fname
&lt;/pre&gt;
On running the above script, we get:&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ ./findmod.py
/usr/lib/python2.7/collections.py&lt;/pre&gt;
&amp;nbsp; &amp;nbsp;&lt;b&gt;sys.path&lt;/b&gt; contains the list of directories from where the modules is picked up. Since the collections module is present in one of these directories, the file is to be checked for existence in every directory. Once found, it is printed.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;os.path.join&lt;/b&gt; -&amp;gt; This joins all the arguments given with the path separator( If Unix flavor, the path separator will be / , if Windows it will be \ ). The advantage of using join rather than normal string conatenation is portability. join will use the appropriate path separator depending on the operating system.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;os.path.isfile&lt;/b&gt; -&amp;gt; This function checks whether a file exists or not.</description><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><author>guru@theunixschool.com (Guru Prasad)</author></item><item><title>Perl : Foreach loop variable is an alias</title><link>http://www.theunixschool.com/2013/07/perl-foreach-loop-variable-is-alias.html</link><category>Perl</category><category>perl alias</category><category>perl foreach</category><pubDate>Fri, 19 Jul 2013 10:16:00 +0530</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-1255024703457423340.post-3394301189875127649</guid><description>&amp;nbsp;In Perl, when an array is traversed using the foreach loop, the variable holding the element of the array during the iteration is actually an alias to the actual element itself. Due to this, any change done to this variable automatically updates the array itself.&lt;br /&gt;
&amp;nbsp;&amp;nbsp; Let us see some examples where every element of an array has to be added by 10:&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;1. Array elements get updated when updating $_&lt;/b&gt;:
&lt;br /&gt;
&lt;pre class="gpr1"&gt;#!/usr/bin/perl
use warnings ;
use strict ;
$\="\n";

my @arr=(5..8);
print "@arr";
foreach (@arr){
        $_+=10;
}
print "@arr";
&lt;/pre&gt;
&amp;nbsp;This snippet when run outputs:&lt;br /&gt;
&lt;pre class="gpr1"&gt;5 6 7 8
15 16 17 18
&lt;/pre&gt;
&amp;nbsp; As seen above, just by updating the $_, the array elements get updated automatically.&lt;br /&gt;
&lt;a name='more'&gt;&lt;/a&gt;&lt;br /&gt;
&lt;b&gt;2. Array elements get updated even when using the holding variable&lt;/b&gt;:
&lt;br /&gt;
&lt;pre class="gpr1"&gt;#!/usr/bin/perl
use warnings ;
use strict ;
$\="\n";

my @arr=(5..8);
print "@arr";
foreach my $x (@arr){
        $x+=10;
}
print "@arr";
&lt;/pre&gt;
&amp;nbsp;&amp;nbsp; Instead of using the special variable $_, this example uses a lexical variable $x to hold the values in iteration.&lt;br /&gt;
The above&amp;nbsp; snippet outputs:&lt;br /&gt;
&lt;pre class="gpr1"&gt;5 6 7 8
15 16 17 18
&lt;/pre&gt;
&lt;br /&gt;
&lt;b&gt;3. List of scalar values also gets updated&lt;/b&gt;:
&lt;br /&gt;
&lt;pre class="gpr1"&gt;#!/usr/bin/perl
use warnings ;
use strict ;
$\="\n";

my ($x,$y,$z)=(20,30,40);

foreach my $a ($x,$y,$z){
        $a+=10;
}
print "$x $y $z";
&lt;/pre&gt;
The sample snippet outputs:
&lt;br /&gt;
&lt;pre class="gpr1"&gt;20 30 40
30 40 50
&lt;/pre&gt;
&amp;nbsp; Even when a set of scalars is given, they too get udpated the same way. The holding variable $a is just an alias to these scalar variables.</description><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><author>guru@theunixschool.com (Guru Prasad)</author></item><item><title>Linux For You - A magazine for Open Source techies</title><link>http://www.theunixschool.com/2013/07/linux-for-you-magazine-for-open-source.html</link><category>review</category><pubDate>Wed, 17 Jul 2013 09:19:00 +0530</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-1255024703457423340.post-813585725012138256</guid><description>&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;a href="http://www.linuxforu.com/"&gt;Linux For You(&lt;/a&gt;LFY) or the OpenSource For You is the magazine which you should be having if you are a techy, especially for the ones working in Unix or Linux flavors. I accidentally got my hands on the magazine once, and made it a point to subscribe to it immediately.&lt;br /&gt;
&lt;br /&gt;
&amp;nbsp; My 5 reasons why it is a must in your shelf:&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;1. Knowledge on Linux World:&lt;/b&gt; Linux is one such technology which has no limits. You keep learning, Linux keeps providing something new for you to satisfy your hunger. However, its not possible to learn everything by ourself through our experiments. It takes lot of time to learn anything by oneself. This magazine&amp;nbsp; is a place wherein you get lot of knowledge, good knowledge, in a short span of time. The topics covered can be of any programming language, scripting language, system administration stuff, apps programming stuff, review of any particular software, etc. Last but not the least, the articles always come with lots of explanation.&lt;br /&gt;
&lt;a name='more'&gt;&lt;/a&gt;&lt;br /&gt;
&lt;b&gt;2. All important Open Source&lt;/b&gt; : Most of the softwares we use today are open source. I use Ubuntu for my desktop, and the rest of the software goes without saying. The fact is, the majority of the softwares coming up these days are open source, and the OpenSource storm has already taken the tech world in a different direction. This will lead to a day wherein each and every electronic item we use in our life will have something of open source associated to it. Hence, it is very important for us to be in the complete know-how of things. The articles on Open Source in the magazine could range from servers, networking, security, tools, etc.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;3. Hot technologies in the market&lt;/b&gt;: Cloud computing, Big data, Hadoop are some of the trending technologies in the market. You like it or not, it cannot be avoided. Very soon, these terminologies are going to find a mention in our day to day life. You will always find dedicated articles on the latest market offerings in LFY. Getting exposed to new technologies will help us grow in this competitive market. Also,&amp;nbsp; a lot of coverage on the Android apps programming is provided which is a hot-cake today. &lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;4. Utilities&lt;/b&gt; : Every developer or admin works on some utilities or the other. And the developer/admin is only aware about those utilities which he or she has come across. Come to LFY, you will see articles on quite a lot of utilities. Though we may not need to know too much about it, having a basic understanding of important ones will always keep us in good stead. Also, with every edition you get a CD of one of the Linux distros enclosed.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;5. Career options:&lt;/b&gt; LFY has a section devoted for career options. This section takes up a hot career option in the market and talks about in detail, about the scope of it, the advantages of the technology, the different training institutes providing training on the technology and of course,the salary range for freshers who want to get into this segment. This section is very helpful for every techy, especially for those who are trying to shift to a new domain.&lt;br /&gt;
&lt;br /&gt;
P.S : I subscribed to this magazine around 6 months back, and I can surely say I gained quite a bit of knowledge of the OpenSource market and its offerings. You always feel you are in sync with the OpenSource world which is more important in today's competitive market.</description><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><author>guru@theunixschool.com (Guru Prasad)</author></item><item><title>Perl : Remove duplicate elements from arrays</title><link>http://www.theunixschool.com/2013/05/perl-remove-duplicate-elements-from.html</link><category>Perl</category><category>perl arrays</category><category>remove duplicates</category><pubDate>Tue, 14 May 2013 10:48:00 +0530</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-1255024703457423340.post-7024827363412366721</guid><description>&lt;span style="font-size: x-large;"&gt;H&lt;/span&gt;ow to remove duplicate element from arrays in Perl? Let us see in this article how can duplicates be removed in different ways?&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;1. Copying distinct elements to new array using grep function&lt;/b&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;my @arr=qw(bob alice alice chris bob);
my @arr1;
foreach my $x (@arr){
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; push @arr1, $x if !grep{$_ eq $x}@arr1;
}
print "@arr1";&lt;/pre&gt;
&amp;nbsp; &amp;nbsp;A loop is run on the array elements. For every element, it is checked to find out whether the element is already present in the new array. If present, it is skipped, else added to the new array.&lt;br /&gt;
&lt;a name='more'&gt;&lt;/a&gt;&lt;br /&gt;
&lt;b&gt;2. Same way using regex&lt;/b&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;my @arr=qw(bob alice alice chris bob);
my @arr1;
foreach my $x (@arr){
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; push @arr1, $x if !grep{/^$x$/}@arr1;
}
print "@arr1";&lt;/pre&gt;
&amp;nbsp; &amp;nbsp;This method is same as the above except that instead of string comparison, the array element is checked using the regular expression.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;3. Using hash&lt;/b&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;my @arr=qw(bob alice alice chris bob);
my %h1;
foreach my $x (@arr){
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; $h1{$x}=1;
}
@arr=keys%h1;
print "@arr";&lt;/pre&gt;
&amp;nbsp; &amp;nbsp;Every element is stored in a &lt;a href="http://www.theunixschool.com/2012/12/10-examples-initializing-hash-perl.html"&gt;hash &lt;/a&gt;with key as the array element and value as 1. Since a hash cannot have duplicate keys, after populating the hash, the keys from the hash will consist of distinct array elements.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;4.Using hash and map function&lt;/b&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;my @arr=qw(bob alice alice chris bob);
my %h1=map{$_=&amp;gt;1}@arr;
@arr=keys%h1;
print "@arr";&lt;/pre&gt;
&amp;nbsp; Same as last example, instead of running a loop on the array elements, the hash is populated using the map function where the array element is the key and the value is 1. Map function returns a key-value pair for every array element where the key is the array element and the value is 1.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;5. Using hash in array context for keys&lt;/b&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;my @arr=qw(bob alice alice chris bob);
my %h1;
@h1{@arr}=(1..@arr);
@arr=keys%h1;
print "@arr";&lt;/pre&gt;
&amp;nbsp; The hash is populated little differently here. Hash can be populated either for a single key-value or for multiple key value pairs.&amp;nbsp;&lt;i&gt;@h1{@arr}=(1..@arr)&lt;/i&gt; translates to&amp;nbsp;&lt;i&gt;@h1{"bob","alice","alice","chris","bob"}=(1,2,3,4,5)&lt;/i&gt;</description><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><author>guru@theunixschool.com (Guru Prasad)</author></item><item><title>Perl - 6 examples to fetch date / time without Linux date command</title><link>http://www.theunixschool.com/2013/04/perl-6-examples-to-fetch-date-time.html</link><category>date</category><category>date functions</category><category>linux date command</category><category>perl date</category><pubDate>Wed, 10 Apr 2013 16:31:00 +0530</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-1255024703457423340.post-1224716880713739451</guid><description>&lt;span style="font-size: x-large;"&gt;H&lt;/span&gt;ow to fetch date and time related stuff within in Perl?&lt;br /&gt;
&amp;nbsp; &amp;nbsp;Sometimes, Perl developers resort to using of Unix system &lt;a href="http://www.theunixschool.com/2012/04/date-gnu-date.html"&gt;date command&lt;/a&gt; to fetch a date or time within Perl script. This is not needed at all since Perl itself has a set of built-ins using which dates and epoch can be retrieved easily without using the system date command. In this article, let us see how to simulate the date related commands in Perl.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;1. Getting the date command output&lt;/b&gt;:&lt;br /&gt;
Linux command:&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ date&lt;/pre&gt;
To get the date command like output in Perl:
&lt;br /&gt;
&lt;a name='more'&gt;&lt;/a&gt;&lt;pre class="gpr1"&gt;my $x=localtime;
print $x;&lt;/pre&gt;
&amp;nbsp; &amp;nbsp;&lt;i&gt;localtime &lt;/i&gt;is a Perl built-in, which when called without any arguments returns the current date and time. The above program will return an output like this:&lt;br /&gt;
&lt;pre class="gpr1"&gt;Wed Apr 10 15:54:10 2013&lt;/pre&gt;
&lt;b&gt;2. Extract only the hour,minute and seconds from the date command&lt;/b&gt;:&lt;br /&gt;
&lt;u&gt;Linux&lt;/u&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ date '+%H%M%S'&lt;/pre&gt;
&lt;u&gt;Perl&lt;/u&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;my ($s,$m,$h)=localtime;
print "$h$m$s";&lt;/pre&gt;
&lt;i&gt;localtime &lt;/i&gt;built-in depends on the context in which it is being used:&lt;br /&gt;
In scalar context, returns the date and time like the Unix date command.&lt;br /&gt;
In list context, returns a list of values : seconds,minutes,hour,day,month(0-11),year,and so on. In the above example, only the seconds, minutes and hours are stored.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;3. Get the Unix(epoch) time&lt;/b&gt;:&lt;br /&gt;
&lt;u&gt;Linux&lt;/u&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ date '+%s'&lt;/pre&gt;
&lt;u&gt;Perl&lt;/u&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;my $tm=time;
print $tm;&lt;/pre&gt;
&amp;nbsp; &amp;nbsp; &lt;i&gt;time &lt;/i&gt;is a perl built-in which gives the &lt;a href="http://www.theunixschool.com/2013/01/what-is-unix-time.html"&gt;Unix Time&lt;/a&gt; (epoch).&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;4. Get yesterday's date&lt;/b&gt;:&lt;br /&gt;
&lt;u&gt;Linux&lt;/u&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ date -d "yesterday" '+%y%m%d'&lt;/pre&gt;
&lt;u&gt;Perl&lt;/u&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;use POSIX qw(strftime);

my $x=strftime("%y%m%d",localtime(time-86400));
print $x;&lt;/pre&gt;
2 things to note:&lt;br /&gt;
&lt;b&gt;a&lt;/b&gt;. &lt;i&gt;localtime&lt;/i&gt; built-in can take a Unix time as an argument and return the date/time for the specific Unix time. In other words, &amp;nbsp;$x=localtime is same as $x=localtime(time) . By subtracting, time with 86400(24*60*60), we get the Unix time of yesterday.&lt;br /&gt;
&lt;b&gt;b&lt;/b&gt;. &lt;i&gt;strftime &lt;/i&gt;is a function which takes a localtime as argument, and formats the result as a string. The format specifiers are similar to the system date command.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;5. Get Unix time(epoch) of yesterday's date&lt;/b&gt;:&lt;br /&gt;
&lt;u&gt;Linux&lt;/u&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ date -d "yesterday" '+%s'&lt;/pre&gt;
&lt;u&gt;Perl&lt;/u&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;my $tm=mktime(localtime(time-86400));
print $tm;&lt;/pre&gt;
&amp;nbsp; mktime is another Perl built-in which can calculate the Unix time for a given localtime. This above snippet calculates the Unix time for the last day.&lt;br /&gt;
&lt;b&gt;6. Get epoch of a specific date/time&lt;/b&gt;:&lt;br /&gt;
&lt;u&gt;Linux&lt;/u&gt;:
&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ date -d "08 May 2012 11AM 30minutes" '+%s'&lt;/pre&gt;
&lt;u&gt;Perl&lt;/u&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;my $tm=mktime(0,30,11,8,4,112);
print $tm;&lt;/pre&gt;
&amp;nbsp; &amp;nbsp;Since &lt;i&gt;mktime &lt;/i&gt;takes the input of the format of localtime command's output, by providing the appropriate date and time as arguments to the &lt;i&gt;mktime&lt;/i&gt;, the Unix time can be calculated for any pre-defined date and time.</description><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><author>guru@theunixschool.com (Guru Prasad)</author></item><item><title>Perl - How to find the sum of digits in a number?</title><link>http://www.theunixschool.com/2013/03/perl-how-to-find-sum-of-digits-in-number.html</link><category>Perl</category><category>perl sum digits</category><pubDate>Tue, 26 Mar 2013 16:10:00 +0530</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-1255024703457423340.post-4011818447518237462</guid><description>&lt;span style="font-size: x-large;"&gt;H&lt;/span&gt;ow 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?&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;1. Divide and accumulate&lt;/b&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;my $x=3456;
my $sum=0;
while ($x) {
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; $sum+=$x%10;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; $x/=10;
}
print $sum;&lt;/pre&gt;
&amp;nbsp; 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.&lt;br /&gt;
&lt;a name='more'&gt;&lt;/a&gt;&lt;br /&gt;
&lt;b&gt;2. Using regular expression&lt;/b&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;my $x=3456;
my @arr=$x=~/./g;
my $sum=0;
$sum+=$_ foreach(@arr);
print $sum;&lt;/pre&gt;
&amp;nbsp; The number is broken into individual digits using the regular expression and extracted into an array. The array elements are looped using the foreach loop and the sum is calculated.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;3. Using eval and join&lt;/b&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;my $x=3456;
my @arr=$x=~/./g;
print eval join "+",@arr;&lt;/pre&gt;
&amp;nbsp;The number is separated into digits as in the last example. Using &lt;i&gt;join&lt;/i&gt;, all the digits are joined using "+" and then the &lt;i&gt;eval &lt;/i&gt;function evaluates the string.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;4. Using CPAN module List::Util&lt;/b&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;use List::Util qw(sum);

my $x=3456;
my @arr=$x=~/./g;
print sum @arr;&lt;/pre&gt;
&amp;nbsp; The CPAN module &lt;a href="http://search.cpan.org/~pevans/Scalar-List-Utils-1.27/lib/List/Util.pm"&gt;List::Util &lt;/a&gt;contains a subroutine &lt;i&gt;sum &lt;/i&gt;which takes an array as input and calculates the returns sum of all elements in the array.</description><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><author>guru@theunixschool.com (Guru Prasad)</author></item><item><title>How to remove leading zeros in a string in Linux?</title><link>http://www.theunixschool.com/2013/03/how-to-remove-leading-zeros-in-string.html</link><category>awk one liners</category><category>ksh</category><category>perl one liners</category><category>remove leading zeros</category><pubDate>Thu, 14 Mar 2013 16:13:00 +0530</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-1255024703457423340.post-2973515498960038714</guid><description>&lt;span style="font-size: x-large;"&gt;H&lt;/span&gt;ow to remove leading zeros in a variable or a string?&lt;br /&gt;
&lt;br /&gt;
Let us consider a variable "x" which has the below value :&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ x=0010
$ echo $x
0010&lt;/pre&gt;
&lt;b&gt;1. Using typeset command of ksh&lt;/b&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ typeset -LZ x
$ x=0010
$ echo $x
10&lt;/pre&gt;
&amp;nbsp; &amp;nbsp;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.&lt;br /&gt;
&lt;a name='more'&gt;&lt;/a&gt;&lt;br /&gt;
&lt;b&gt;2. Using sed command&lt;/b&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ echo $x | sed 's/^0*//'
10&lt;/pre&gt;
&amp;nbsp; &amp;nbsp; The expression '^0*' will search for a sequence of 0's in the beginning and delete them.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;3. Using awk&lt;/b&gt; :&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ echo $x | awk '{sub(/^0*/,"");}1'
10&lt;/pre&gt;
&amp;nbsp; &amp;nbsp; Using the sub function of awk, explanation same as sed solution.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;4. awk with printf&lt;/b&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ echo $x| awk '{printf "%d\n",$0;}'
10&lt;/pre&gt;
&amp;nbsp; &amp;nbsp;Using &lt;i&gt;printf&lt;/i&gt;, use the integer format specifier %d, the leading zeros get stripped off automatically.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;5. awk using int&lt;/b&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ echo $x | awk '{$0=int($0)}1'
10&lt;/pre&gt;
&amp;nbsp; &amp;nbsp; The &lt;i&gt;int &lt;/i&gt;function converts a expression into a integer.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;6. Perl using regex&lt;/b&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ echo $x | perl -pe 's/^0*//;'
10&lt;/pre&gt;
&lt;br /&gt;
&lt;b&gt;7. Perl with printf&lt;/b&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ echo $x | perl -ne 'printf "%d\n",$_;'
10&lt;/pre&gt;
&lt;br /&gt;
&lt;b&gt;8. Perl with int&lt;/b&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ echo $x | perl -pe '$_=int;'
10&lt;/pre&gt;
</description><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">7</thr:total><author>guru@theunixschool.com (Guru Prasad)</author></item><item><title>Perl - What is __DATA__ ?</title><link>http://www.theunixschool.com/2013/02/perl-what-is-data.html</link><category>__DATA__</category><category>__END__</category><category>Perl</category><category>perl DATA handler</category><category>perl file handling</category><pubDate>Tue, 26 Feb 2013 16:03:00 +0530</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-1255024703457423340.post-3253051547271287819</guid><description>&lt;span style="font-size: x-large;"&gt;W&lt;/span&gt;hat is __DATA__ ? Why is it used?&lt;br /&gt;
&amp;nbsp; &amp;nbsp; Generally, Perl reads data from a file which in the Perl program can be accessed using &lt;i&gt;open &lt;/i&gt;and &lt;i&gt;readline &lt;/i&gt;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 &lt;i&gt;open &lt;/i&gt;and &lt;i&gt;readline &lt;/i&gt;functions. The solution for this : __DATA__.&lt;br /&gt;
&lt;br /&gt;
&amp;nbsp; &amp;nbsp;Let us consider a sample text file:&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ cat f1.txt
AIX,1
Solaris,2
Unix,3
Linux,4&lt;/pre&gt;
&lt;a name='more'&gt;&lt;/a&gt;&lt;br /&gt;
&lt;b&gt;1. The common way of reading or processing a file in Perl:&lt;/b&gt;&lt;br /&gt;
&lt;pre class="gpr1"&gt;#!/usr/bin/perl
use warnings;
use strict;

open my $fh, '&amp;lt;', 'f1.txt' or die 'Cannot open f1.txt';

while(&amp;lt;$fh&amp;gt;){
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; print;
}
close ($fh);&lt;/pre&gt;
&amp;nbsp; &lt;i&gt;open &lt;/i&gt;function opens the file and associates the file with the filehandler $fh. This file handler with diamond(&amp;lt;&amp;gt; )operator reads a line from the file. Using &lt;i&gt;while &lt;/i&gt;loop, the entire file is read and printed till the end of the file is reached. &lt;i&gt;close &lt;/i&gt;function closes the file associated with the file handler.&amp;nbsp;This method is little cumbersome in a way that every time to read a file, one needs to have open and close commands.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;2. &amp;nbsp;Using __DATA__ : Input file content in the source file itself&lt;/b&gt;:&lt;br /&gt;
Let us see how to use this:&lt;br /&gt;
&lt;pre class="gpr1"&gt;#!/usr/bin/perl

use warnings;
use strict;

while(&amp;lt;DATA&amp;gt;){
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; print;
}

__DATA__
AIX,1
Solaris,2
Unix,3
Linux,4&amp;nbsp;&amp;nbsp;&lt;/pre&gt;
&lt;b&gt;&amp;nbsp;__DATA__&lt;/b&gt; &amp;nbsp;:&lt;br /&gt;
&amp;nbsp; &amp;nbsp;Any input data to be provided to the Perl program is put below the line __DATA__ . This __DATA__ line indicates that the content following is input file content. Perl automatically attaches the DATA file handler to access this data for the programmer which can then be read &amp;nbsp;with the diamond operator(&amp;lt;&amp;gt;) . This section should be put only at the very end of the program.&lt;br /&gt;
Note:&amp;nbsp;Perl allows to use __END__ as well in place of __DATA__. However, the file handler associated will be DATA itself.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;&amp;nbsp;Reading entire file into an array&lt;/b&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;#!/usr/bin/perl

use warnings;
use strict;

my @arr=&amp;lt;DATA&amp;gt;;
print @arr;

__DATA__
AIX,1
Solaris,2
Unix,3
Linux,4&lt;/pre&gt;
&amp;nbsp; &amp;nbsp;Just by assigning the DATA handler to an array (for that matter any file handler), the entire file will be read into the array. By loading the entire file into an array, any particular record of a file can be accessed &amp;nbsp;from the array.</description><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">1</thr:total><author>guru@theunixschool.com (Guru Prasad)</author></item><item><title>What is the time command in Linux for?</title><link>http://www.theunixschool.com/2013/02/what-is-time-command-in-linux-for.html</link><category>time command</category><category>unix time</category><pubDate>Tue, 19 Feb 2013 16:53:00 +0530</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-1255024703457423340.post-5051821723370299694</guid><description>&lt;b&gt;time &lt;/b&gt;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.&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ time

real &amp;nbsp; &amp;nbsp;0m0.000s
user &amp;nbsp; &amp;nbsp;0m0.000s
sys &amp;nbsp; &amp;nbsp; 0m0.000s&lt;/pre&gt;
time command output shows 3 different components:&lt;br /&gt;
real - The total time elapsed during the command which includes the time taken for the process.&lt;br /&gt;
user - The time taken for the process only in the user space. This does not include kernel calls.&lt;br /&gt;
sys - The time taken for the process in system space (for kernel related calls )&lt;br /&gt;
&lt;a name='more'&gt;&lt;/a&gt;&lt;br /&gt;
&lt;b&gt;1. Using time for a command&lt;/b&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ time ls
f1.c &amp;nbsp;f2.c

real &amp;nbsp; &amp;nbsp;0m0.01s
user &amp;nbsp; &amp;nbsp;0m0.00s
sys &amp;nbsp; &amp;nbsp; 0m0.01s&lt;/pre&gt;
&amp;nbsp; This indicates the &lt;a href="http://www.theunixschool.com/2010/09/5-different-ways-to-do-file-listing.html"&gt;ls &lt;/a&gt;command has taken a total of 0.01 second to finish, which is the time elapsed.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;2. Using time command for a simple script:&lt;/b&gt;&lt;br /&gt;
Let us write a script, try.sh, which prints a welcome message:&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ cat try.sh
#!/bin/bash

echo "welcome"&lt;/pre&gt;
Running the time command:&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ time ./try.sh
welcome

real &amp;nbsp; &amp;nbsp;0m0.03s
user &amp;nbsp; &amp;nbsp;0m0.01s
sys &amp;nbsp; &amp;nbsp; 0m0.02s&lt;/pre&gt;
&amp;nbsp; This script has taken a total of 0.03 seconds to execute.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;3. Timing the sleep in the script&lt;/b&gt;:&lt;br /&gt;
&lt;b&gt;&amp;nbsp; &lt;/b&gt;sleep command's duration do not go against user or sys, it is always against the real output.&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ cat try.sh
#!/bin/bash

sleep 3
echo "welcome"&lt;/pre&gt;
Running the time command:&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ time ./try.sh
welcome

real &amp;nbsp; &amp;nbsp;0m3.04s
user &amp;nbsp; &amp;nbsp;0m0.03s
sys &amp;nbsp; &amp;nbsp; 0m0.01s&lt;/pre&gt;
&lt;div&gt;
&amp;nbsp; &amp;nbsp;As seen above, the sleep duration goes entirely in the real, not in the user or sys.&lt;/div&gt;
&lt;br /&gt;
&lt;b&gt;&lt;u&gt;Capturing time output&lt;/u&gt;&lt;/b&gt;:&lt;br /&gt;
&amp;nbsp; time command output is re-directed to standard error terminal, and not standard output like other Unix commands. Hence, time command output cannot be re-directed to a file in a normal way.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;1. To retrieve only the real time of the time output&lt;/b&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ time ./try.sh | grep real
welcome

real &amp;nbsp; &amp;nbsp;0m1.05s
user &amp;nbsp; &amp;nbsp;0m0.02s
sys &amp;nbsp; &amp;nbsp; 0m0.04s&lt;/pre&gt;
As seen, grep does not help since the time command output is not in the STDOUT.&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ (time ./try.sh) 2&amp;gt;&amp;amp;1 | grep real
real &amp;nbsp; &amp;nbsp;0m1.05s&lt;/pre&gt;
&amp;nbsp; &amp;nbsp;By re-directing the &lt;a href="http://www.theunixschool.com/2010/08/unix-file-descriptors.html"&gt;standard error to standard output,&lt;/a&gt; the time command output can now be passed as standard input to other commands.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;2. To re-direct the time command output to a file&lt;/b&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ (time ls ) 2&amp;gt;file
&lt;/pre&gt;
</description><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><author>guru@theunixschool.com (Guru Prasad)</author></item><item><title>sed - 10 examples to replace / delete / print lines of CSV file</title><link>http://www.theunixschool.com/2013/02/sed-examples-replace-delete-print-lines-csv-files.html</link><category>parse CSV file</category><category>sed</category><category>sed one liners</category><category>sed regular expression</category><pubDate>Tue, 12 Feb 2013 16:25:00 +0530</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-1255024703457423340.post-7345296695259990364</guid><description>&lt;span style="font-size: x-large;"&gt;H&lt;/span&gt;ow to use &lt;a href="http://www.theunixschool.com/p/awk-sed.html"&gt;sed &lt;/a&gt;to work with a CSV file? Or How to work with any file in which fields are separated by a delimiter?&lt;br /&gt;
&lt;br /&gt;
Let us consider a sample CSV file with the following content:&lt;br /&gt;
&lt;pre class="gpr1"&gt;cat file
Solaris,25,11
Ubuntu,31,2
Fedora,21,3
LinuxMint,45,4
RedHat,12,5&lt;/pre&gt;
&lt;br /&gt;
&lt;b&gt;1. To remove the 1st field or column&lt;/b&gt; :&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ sed 's/[^,]*,//' file
25,11
31,2
21,3
45,4
12,5&lt;/pre&gt;
&amp;nbsp; &amp;nbsp;This regular expression searches for a sequence of non-comma([^,]*) characters and deletes them which results in the 1st field getting removed.&lt;br /&gt;
&lt;a name='more'&gt;&lt;/a&gt;&lt;br /&gt;
&lt;b&gt;2. To print only the last field, OR remove all fields except the last field&lt;/b&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ sed 's/.*,//' file
11
2
3
4
5&lt;/pre&gt;
&amp;nbsp; This regex removes everything till the last comma(.*,) which results in deleting all the fields except the last field.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;3. To print only the 1st field&lt;/b&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ sed 's/,.*//' file
Solaris
Ubuntu
Fedora
LinuxMint
RedHat&lt;/pre&gt;
&amp;nbsp; &amp;nbsp; This regex(,.*) removes the characters starting from the 1st comma till the end resulting in deleting all the fields except the last field.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;4. To delete the 2nd field&lt;/b&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ sed 's/,[^,]*,/,/' file
Solaris,11
Ubuntu,2
Fedora,3
LinuxMint,4
RedHat,5&lt;/pre&gt;
&amp;nbsp; &amp;nbsp; The regex (,[^,]*,) &amp;nbsp;searches for a comma and sequence of characters followed by a comma which results in matching the 2nd column, and replaces this pattern matched with just a comma, ultimately ending in deleting the 2nd column.&lt;br /&gt;
Note: To delete the fields in the middle gets more tougher in sed since every field has to be matched literally.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;5. To print only the 2nd field&lt;/b&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ sed 's/[^,]*,\([^,]*\).*/\1/' file
25
31
21
45
12&lt;/pre&gt;
&lt;div&gt;
&amp;nbsp; &amp;nbsp;The regex matches the first field, second field and the rest, however groups the 2nd field alone. The whole line is now replaced with the 2nd field(\1), hence only the 2nd field gets displayed.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;6. Print only lines in which the last column is a single digit number&lt;/b&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ sed -n '/.*,[0-9]$/p' file
Ubuntu,31,2
Fedora,21,3
LinuxMint,45,4
RedHat,12,5&lt;/pre&gt;
&lt;div&gt;
&amp;nbsp; The regex (,[0-9]$) checks for a single digit in the last field and the&lt;i&gt; p &lt;/i&gt;command prints the line which matches this condition.&lt;/div&gt;
&lt;br /&gt;
&lt;b&gt;7. To number all lines in the file&lt;/b&gt;:
&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ sed = file | sed 'N;s/\n/ /'
1 Solaris,25,11
2 Ubuntu,31,2
3 Fedora,21,3
4 LinuxMint,45,4
5 RedHat,12,5
&lt;/pre&gt;
&amp;nbsp; &amp;nbsp; This is simulation of &lt;i&gt;cat -n&lt;/i&gt; command. awk does it easily using the special variable NR. The '=' command of sed gives the line number of every line followed by the line itself. The sed output is piped to another sed command to &lt;a href="http://www.theunixschool.com/2012/03/join-every-2-lines-in-file.html"&gt;join every 2 lines&lt;/a&gt;.&lt;/div&gt;
&lt;br /&gt;
&lt;b&gt;8. Replace the last field by 99 if the 1st field is 'Ubuntu'&lt;/b&gt;:

&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ sed 's/\(Ubuntu\)\(,.*,\).*/\1\299/' file
Solaris,25,11
Ubuntu,31,99
Fedora,21,3
LinuxMint,45,4
RedHat,12,5
&lt;/pre&gt;
&amp;nbsp; This regex matches 'Ubuntu' and till the end except the last column and groups each of them as well. In the replacement part, the 1st and 2nd group along with the new number 99 is substituted.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;9. Delete the 2nd field if the 1st field is 'RedHat'&lt;/b&gt;:

&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ sed 's/\(RedHat,\)[^,]*\(.*\)/\1\2/' file
Solaris,25,11
Ubuntu,31,2
Fedora,21,3
LinuxMint,45,4
RedHat,,5&lt;/pre&gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; The 1st field 'RedHat', the 2nd field and the remaining fields are grouped, and the replacement is done with only 1st and the last group , resuting in getting the 2nd field deleted.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;10. To insert a new column at the end(last column)&lt;/b&gt; :&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ sed 's/.*/&amp;amp;,A/' file
Solaris,25,11,A
Ubuntu,31,2,A
Fedora,21,3,A
LinuxMint,45,4,A
RedHat,12,5,A&lt;/pre&gt;
&amp;nbsp; &amp;nbsp;The regex (.*) matches the entire line and replacing it with the line itself (&amp;amp;) and the new field.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;11. To insert a new column in the beginning(1st column)&lt;/b&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ sed 's/.*/A,&amp;amp;/' file
A,Solaris,25,11
A,Ubuntu,31,2
A,Fedora,21,3
A,LinuxMint,45,4
A,RedHat,12,5&lt;/pre&gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp;Same as last example, just the line matched is followed by the new column.&lt;br /&gt;
&lt;br /&gt;
Note: &lt;a href="http://www.theunixschool.com/p/awk-sed.html"&gt;sed &lt;/a&gt;is generally not preferred on files which has fields separated by a delimiter because it is very difficult to access fields in sed unlike &lt;a href="http://www.theunixschool.com/p/awk-sed.html"&gt;awk &lt;/a&gt;or Perl&amp;nbsp;where splitting fields is a breeze.</description><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">6</thr:total><author>guru@theunixschool.com (Guru Prasad)</author></item><item><title>How to delete every nth line in a file in Linux?</title><link>http://www.theunixschool.com/2013/02/how-to-delete-every-nth-line-in-file-in.html</link><category>awk one liners</category><category>delete line</category><category>perl one liners</category><category>sed one liners</category><pubDate>Wed, 6 Feb 2013 16:37:00 +0530</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-1255024703457423340.post-5762911412582864329</guid><description>&lt;span style="font-size: x-large;"&gt;H&lt;/span&gt;ow to delete or remove every nth line in a file? The requirement is to remove every 3rd line in the file.&lt;br /&gt;
&lt;br /&gt;
Let us consider a file with the below content.&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ cat file
AIX
Solaris
Unix
Linux
HPUX&lt;/pre&gt;
&lt;br /&gt;
&lt;b&gt;1. awk solution&lt;/b&gt; :&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ awk 'NR%3' file
AIX
Solaris
Linux
HPUX&lt;/pre&gt;
&amp;nbsp; &amp;nbsp;&lt;i&gt;NR%3&lt;/i&gt; will be true for any line number which is not multiple of 3, and hence the line numbers which are multiple's of 3 does not get printed. &lt;br /&gt;
Note: &lt;i&gt;NR%3&lt;/i&gt; is same as &lt;i&gt;NR%3!=0&lt;/i&gt;&lt;br /&gt;
&lt;a name='more'&gt;&lt;/a&gt;&lt;br /&gt;
&lt;b&gt;2. Perl&lt;/b&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ perl -lne 'print if $.%3 ;' file
AIX
Solaris
Linux
HPUX&lt;/pre&gt;
&amp;nbsp; Same logic as awk solution. &lt;i&gt;$.&lt;/i&gt; in perl contains the line number of the file.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;3. sed&lt;/b&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ sed 'n;n;d;' file
AIX
Solaris
Linux
HPUX&lt;/pre&gt;
&amp;nbsp; &lt;i&gt;n&lt;/i&gt; commands prints the current line and reads the next line. Hence 2 consecutive &lt;i&gt;n&lt;/i&gt;'s result in 2 lines getting printed with the 3rd line in the pattern space. &lt;i&gt;d&lt;/i&gt; command deletes the line(3rd line) which is present in the pattern space. And this continues till the end of the file.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;4. Bash Shell script&lt;/b&gt;:&lt;br /&gt;
&lt;pre class="gpr1"&gt;$ x=0
$ while read line
&amp;gt; do
&amp;gt; &amp;nbsp; ((x++))
&amp;gt; &amp;nbsp; [ $x -eq 3 ] &amp;amp;&amp;amp; { x=0; continue; }
&amp;gt; &amp;nbsp; echo $line
&amp;gt; done &amp;lt; file
AIX
Solaris
Linux
HPUX&lt;/pre&gt;
&amp;nbsp; A simple logic of incrementing a variable by 1 after every line is processed. When the count becomes 3, the particular line is not printed and the counter is reset.</description><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><author>guru@theunixschool.com (Guru Prasad)</author></item></channel></rss>