Tuesday, February 23, 2010

System Software LAB - Exercise 3

Exercise No : 3 grep, awk, sed

Aim :

To demonstrate the use of grep , awk and sed

Description:

1. Using grep command

Grep command used to filter the data. Example in the redhat.txt file it has the word rhel5. You can list out line with has the word rhel5. So the grep command is used for this purpose.

Shell Program
$ cat>god
god is great
god is present everywhere
[2]+ Stopped cat>god

Create a shell script with file name grep1.sh

echo “displaying a string from a file”
echo “get file name”
read s
echo “get string”
read i
grep $i $s

OUTPUT

$ grep.sh

displaying a string from a file
get file name
god
get string
great
god is great


2. Using awk command

cut and awk may both be used to select a specific field from the output of a command. A typical application would be to create a list of currently logged-in users:

Create a shell script with file name cut1.sh

#!/bin/sh
#
# using cut:
USERS=`who | cut -f1 -d" "`
echo "Users on the system are: $USERS."


Create a shell script with file name awk1.sh

# using awk:
USERS=`who | awk '{print $1}'`
echo "Users on the system are: $USERS."

In the first example, cut takes its input from the who command. -f1 specifies that the first field is to be cut out from each line, and -d" " specifies that the field delimiter is a space.

In the second example, awk takes its input the same way cut did, then prints the first field (space is the default field delimiter for awk). In general, cut is a much simpler command to use. awk is a full language; scripts can be written using awk as the language instead of the shell script.

3. Using sed editor

Sed is the ultimate stream editor. If that sounds strange, picture a stream flowing through a pipe. Sed has several commands, but most people only learn the substitute command: s. The substitute command changes all occurrences of the regular expression into a new value. A simple example is changing "day" in the "old" file to "night" in the "new" file:

sed s/day/night/ new

Or another way (for Unix beginners),

sed s/day/night/ old >new

and for those who want to test this:

echo day | sed s/day/night/

This will output "night".

Using og quote around argument is recommended. Using the strong (single quote) character, that would be:

sed 's/day/night/' new

The sed editor changes exactly what you tell it to. So if you executed

echo Sunday | sed 's/day/night/' new

This would output the word "Sunnight" bacause sed found the string "day" in the input.

There are four parts to this substitute command:

s -> Substitute command
/../../ -> Delimiter
day -> Regular Expression Pattern Search Pattern
night -> Replacement string

The search pattern is on the left hand side and the replacement string is on the right hand side.

No comments:

Post a Comment