Linux Tips and Tricks

Linux Tips and Tricks

Print Random word using the Dictionary file – AWK

September16

Most of the Debian system has the below dictionary file ( which is the pure ASCII words )

/usr/share/dict/american-english

we have a built-in variable called RANDOM in bash and ksh shells. Using that, we can print random words from the above given dictionary file.

example of RANDOM variable

1
2
3
4
$ echo $RANDOM
30728
$ echo $RANDOM
24228

Using the below code, we can print some random word from the dictionary file.

1
2
3
4
5
6
7
8
9
10
$ awk -v lineno="$RANDOM" 'lineno==NR{print;exit}' /usr/share/dict/american-english
Jeannie's
$ awk -v lineno="$RANDOM" 'lineno==NR{print;exit}' /usr/share/dict/american-english
authorization
$ awk -v lineno="$RANDOM" 'lineno==NR{print;exit}' /usr/share/dict/american-english
Yiddish's
$ awk -v lineno="$RANDOM" 'lineno==NR{print;exit}' /usr/share/dict/american-english
Constantine's
$ awk -v lineno="$RANDOM" 'lineno==NR{print;exit}' /usr/share/dict/american-english
Miro

In the above awk command, lineno is a variable which holds the RANDOM number, then we are comparing with processing line number of awk. If both number matches, we are printing that word.
exit is used to avoid processing/reading the remaining lines.

posted under Uncategorized | No Comments »

Find most commonly used commands in your system

September15

The below one liner is used to show the most commonly commands and its count.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$ history | awk '{a[$2]++;next}END{for (i in a){print i " --> " a[i]}}' | sort -nr -k3
clear --> 25
cal --> 23
history --> 9
./caldate.sh --> 7
date --> 6
ls --> 2
cd --> 2
pwd --> 1
ps --> 1
man --> 1
env --> 1
echo|awk --> 1
echo --> 1
chmod --> 1
cat --> 1
awk --> 1
posted under Uncategorized | No Comments »

Retrieve IP Address from URL – nslookup

September12

In unix/linux we have a utility called nslookup. Which is very useful to query internet naming servers.

Man Page for nslookup

1) Lets see how to retrieve the ip address from the URL ( eg. www.google.com )

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$ nslookup www.google.com
Server:        218.186.2.16
Address:    218.186.2.16#53
 
Non-authoritative answer:
Name:    www.google.com
Address: 173.194.38.147
Name:    www.google.com
Address: 173.194.38.146
Name:    www.google.com
Address: 173.194.38.145
Name:    www.google.com
Address: 173.194.38.144
Name:    www.google.com
Address: 173.194.38.148

If you want only the ip address, then you can awk the output of the nslookup output.

1
2
3
4
5
6
7
8
9
$ nslookup www.google.com | awk '/Address/&&!/#/'
Address: 173.194.38.176
Address: 173.194.38.179
Address: 173.194.38.180
Address: 173.194.38.178
Address: 173.194.38.177
 
$ nslookup www.facebook.com | awk '/Address/&&!/#/'
Address: 66.220.149.94

If you type the above ip addresses, then you will be directed to corresponding website.

posted under Uncategorized | No Comments »

Find Weather using perl script Weather::Google

August8

Find Weather using perl script Weather::Google

1) Install the Weather::Google using the Synaptic Package Manager (in Ubuntu)

2) copy paste the below code and save it as googleweather.pl

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#!/usr/bin/perl
use Weather::Google;
 
# If you plan on using locations with non-ASCII characters
use encoding 'utf8';
 
my $gw;
 
## Initialize the module
$gw = new Weather::Google('Singapore'); # City name
 
## Get some current information
 
my @info;
@info = $gw->current('temp_f','temp_c','humidity','wind_condition');
 
## Forecast
 
print "Today's high: ", $gw->forecast(0,'high'),"\n";
print "Today's low: ", $gw->forecast(0,'low'),"\n";
 
## Forecast information:
my $info = $gw->forecast_information;
print "Zip: " . $info->{postal_code}."\n";
 
3) Execute the code using perl googleweather.pl
1
2
3
4
$ perl googleweather.pl
Today's high: 90
Today's low: 77
Zip: Singapore

If you want to install the package in windows then issue the below command in command prompt

1
 ppm install Weather-Google
posted under Uncategorized | No Comments »

Rename the files using perl script

August7

Rename the files using perl

we can use the method rename for renaming the files using perl script.

1
2
3
4
5
6
7
8
9
10
11
$ cat rename.pl
#!/usr/bin/perl
 
use strict;
use warnings;
 
foreach $_ (@ARGV) {
my $oldfile = $_;
s/.bk//g;
rename($oldfile, $_);
}

Now i am creating some .bk files using the touch command

1
2
3
$ touch a.txt.bk
$ touch b.txt.bk
$ touch c.txt.bk

Now i have 3 .bk files in my current directory.

1
2
3
4
5
6
$ ls -lrt
total 4
-rw-rw-r-- 1 kamaraj kamaraj 126 Aug 7 23:38 rename.pl
-rw-rw-r-- 1 kamaraj kamaraj 0 Aug 7 23:38 a.txt.bk
-rw-rw-r-- 1 kamaraj kamaraj 0 Aug 7 23:38 b.txt.bk
-rw-rw-r-- 1 kamaraj kamaraj 0 Aug 7 23:38 c.txt.bk

execute the perl file as below.

1
$ perl rename.pl *.bk

Now you can see all the files are named ( .bk was removed )

1
2
3
4
5
6
$ ls -lrt
total 4
-rw-rw-r-- 1 kamaraj kamaraj 126 Aug 7 23:38 rename.pl
-rw-rw-r-- 1 kamaraj kamaraj 0 Aug 7 23:38 a.txt
-rw-rw-r-- 1 kamaraj kamaraj 0 Aug 7 23:38 b.txt
-rw-rw-r-- 1 kamaraj kamaraj 0 Aug 7 23:38 c.txt

If i want to revert back the filenames to .bk format, then you can use the below one-liner

1
2
3
4
5
6
7
8
$ ls *.txt | perl -lane '$origname=$_;s/.txt/.txt.bk/;rename($origname,$_)'
 
$ ls -lrt
total 4
-rw-rw-r-- 1 kamaraj kamaraj 0 Aug 7 23:38 a.txt.bk
-rw-rw-r-- 1 kamaraj kamaraj 0 Aug 7 23:38 b.txt.bk
-rw-rw-r-- 1 kamaraj kamaraj 0 Aug 7 23:38 c.txt.bk
-rw-rw-r-- 1 kamaraj kamaraj 126 Aug 7 23:42 rename.pl

Using the below for loop, we can easily rename the .txt.bk files to .txt files

1
for i in *.bk; do echo "mv ${i} ${i/.bk/}"; done
posted under Uncategorized | No Comments »

Retrieve File Permission In Octal Representation – Shell Scripting

June25

In most of the linux flavors, you will be having a command called ‘stat’

Using the stat command, we can easily retrieve the permission of a file in octal representation

1
stat -c '%a' filename.txt
Octal digit Text equivalent Binary value Meaning
0 --- 000 All types of access are denied
1 --x 001 Execute access is allowed only
2 -w- 010 Write access is allowed only
3 -wx 011 Write and execute access are allowed
4 r-- 100 Read access is allowed only
5 r-x 101 Read and execute access are allowed
6 rw- 110 Read and write access are allowed
7 rwx 111 Everything is allowed

we can write a awk function to calculate the permission  in octal representation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
$cat permission.awk
function cal(str)
{
    a=0;
    if(str~/r/)
    {
        a+=4;
    }
    if(str~/w/)
    {
        a+=2;
    }
    if(str~/x/)
    {
        a+=1;
    }
}
{
for(i=2;<=length($1);i=i+3)
{
	cal(substr($1,i,3))
	octal=octal""a;
}
print octal
}
1
2
3
4
5
6
7
8
9
10
11
$ chmod 000 a.txt 
$ ls -l a.txt | awk -f permission.awk 
000 
 
$ chmod 001 a.txt 
$ ls -l a.txt | awk -f permission.awk 
001 
 
$ chmod 031 a.txt 
$ ls -l a.txt | awk -f permission.awk 
031

One more function from ctsgnb

1
2
3
4
5
6
7
8
9
10
11
12
13
#!/bin/bash
 
function conv_perm(){
  binary1=`echo "$1" | cut -c4,7,10|tr xstST- 011110`
  binary2=`echo "$1" | cut -c2-10 | tr rwsxtST- 11111000`
  octal=`echo "obase=8;ibase=2;${binary1}${binary2}"|bc`
  echo "$octal"
}
 
#Call the function
conv_perm "-rwxrwxrwx"
conv_perm "-r-x-wx-wx"
conv_perm "-r-x--x-w-"
posted under Uncategorized | No Comments »

Scramble Word Finder – Shell Script

June19

Scramble Word Finder – Shell Script

Most of the Debian system has the below dictionary file ( which is the pure ASCII words )

/usr/share/dict/american-english

Now sort each string by character wise and store it in seperate file called words_sorted.txt

1
perl -lane '@chars=split(//,$_); printf("%s%25s\n",$_,lc join (/,/, sort @chars));'  /usr/share/dict/american-english > words_sorted.txt

Now all the words are sorted and the original word is in first column and the sorted value is in second column.

1
2
3
4
5
6
7
8
9
10
11
$ head words_sorted.txt
 
A                        a
A's                      'as
AOL                      alo
AOL's                    'alos
Aachen                   aacehn
Aachen's                 'aacehns
Aaliyah                  aaahily
Aaliyah's                'aaahilsy
Aaron                    aanor

Now write a script to find the scramble words.

Save the below script as scramble.sh

1
2
3
4
5
6
7
8
9
10
11
12
#!/bin/bash
 
echo -n "Enter the Scrambled Word : "
read word
 
#sort the characters within the word
sorted_word=$(echo "$word" | grep -o . | sort |tr -d "\n")
 
matched_words=$(awk -v word="$sorted_word" '{if($2~word && length($2) == length(word)){print $1}}' words_sorted.txt)
 
echo "Given Input : $word"
echo "The Matched words are : $matched_words"

Now the run the script and check the output

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$ ./scramble.sh
Enter the Scrambled Word : tleeivisno
Given Input : tleeivisno
The Matched words are : television
 
$ ./scramble.sh           
Enter the Scrambled Word : ifnd
Given Input : ifnd
The Matched words are : find
 
$ ./scramble.sh
Enter the Scrambled Word : srbcalme
Given Input : srbcalme
The Matched words are : clambers
scramble

How to solve the Crossword Puzzle ?

Here is the script

https://www.thelinuxtips.com/2010/12/solve-the-crossword-puzzle/

posted under Uncategorized | No Comments »

Linux Commands – Man Page

June18

thelinuxtips.com – Linux Commands Manual Page

man is the system’s manual pager. Each page argument given to man is normally the name of a program, utility or function. The manual page associated with each of these arguments is then found and displayed. A section, if provided, will direct man to look only in that section of the manual. The default action is to search in all of the available sections, following a pre-defined order and to show only the first page found, even if page exists in several sections.

The UNIX Programmer’s Manual was first published on November 3, 1971. The first actual man pages were written by Dennis Ritchie and Ken Thompson at the insistence of Doug McIlroy in 1971. The troff macros used for man pages (-mm) were the general-purpose ones written by Ted Dolotta (later to be the first manager of USG and the principal author of the System III manual), with additions for the manuals. At the time, the availability of online documentation through the manual page system was regarded as a great advance. To this day, virtually every Unix command line application comes with its man page, and many Unix users perceive a lack of man pages as a sign of low quality; indeed, some projects, such as Debian, go out of their way to write man pages for programs lacking one.

More…

I extracted all the man pages and hosted in this website for your reference.

https://www.thelinuxtips.com/Man/

 

posted under Uncategorized | No Comments »

Shell Script to Ping Multiple Hosts

June7

The following script is used to ping multiple hosts.

#!/bin/bash
for i in 192.168.0.{1..10}
do
   ping -c 1 -t 1 "$i" >/dev/null 2>&1 &&
   echo "Ping Status of $i : Success" ||
   echo "Ping Status of $i : Failed"
done

Suppose, if we have more host names in the text file, then we can use the below script.

1
2
3
4
5
6
while read hostname
do
ping -c 1 -t 1 "$hostname" > /dev/null 2>&1 && 
echo "Ping Status of $hostname : Success" || 
echo "Ping Status of $hostname : Failed" 
done < host.txt
posted under Uncategorized | 2 Comments »

Tower of Hanoi – in Shell Script

June4

What is Tower of Hanoi ?

The objective of the puzzle is to move the entire stack to another rod, obeying the following rules:

  •     Only one disk may be moved at a time.
  •     Each move consists of taking the upper disk from one of the rods and sliding it onto another rod, on top of the other disks that may already be present on that rod.
  •     No disk may be placed on top of a smaller disk.

With three disks, the puzzle can be solved in seven moves.

More information  about the Tower of Hanoi

Shell script for this puzzle

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$ cat hanoi.sh
#!/bin/bash
#---------------------------------------
#Author : Kamaraj Subramanian
#---------------------------------------
echo -n "How Many Disks? : "
read disk
echo "-------------STARTS---------"
for (( x=1; x < (1 << $disk ); x++ ))
do
i=$((($x & $x - 1 ) % 3))
j=$(((($x | $x - 1 ) + 1 ) % 3))
echo "Move from tower $i to tower $j"
done

Solution :

1
2
3
4
5
6
7
8
9
10
$ ./hanoi.sh
How Many Disks? : 3
-------------STARTS---------
Move from tower 0 to tower 2
Move from tower 0 to tower 1
Move from tower 2 to tower 1
Move from tower 0 to tower 2
Move from tower 1 to tower 0
Move from tower 1 to tower 2
Move from tower 0 to tower 2
posted under Uncategorized | No Comments »
« Older EntriesNewer Entries »

Recent Comments

    Categories