Sunteți pe pagina 1din 15

SED COMMAND

EXAMPLES

SED SYNTAX
sed [options] <address
actionlist> < filelist>
Options may be
E,f,n

Address action list may be:


Q,d,p,s

File list is any file or file_names

Step 1 : create a file (emp_code) as follows


$ cat > emp_code

Dilip : 562
Harish : 621
Lalitha : 245
Prakash : 120
Rohini : 364
Uday : 864
(ctrl+d save and exit)
Now, from the above file (emp_code)

Question 1: display only 3 records from


emp_code by using sed
$ sed 3q emp_code
Dilip : 562
Harish : 621
Lalitha : 245
On execution of the above command,
first three lines are displayed

$ sed - e 1d -e 2q emp_code
Harish : 621
On execution of the above command,
First line is deleted using the
command 1d

Now, create another file quotes as follows:


$ cat >quotes
She Sells Sea Shells down by the Sea Shore
(ctrl+d)
$ sed - n s/sea/grape/gp quotes
She Sells Grape Shells down by the Grape
Shore
On execution of the above command, Sea
is substituted with Grape

Awk-command
awk - an advanced filter.
created by Aho, Weinberger & Kernighan
awk is not just a command,
its a general purpose programming language that is designed for
processing text-based data, either in files or data streams.
The general syntax of awk command is

$ awk [options] program <filenames>


where,
options : are f and F.
The F option specifies the input field separator,
f informs that the program is on a separate file.

Filenames : Contains the list of zero or more input filenames.


Program : has the general format.

The structure of awk program consists


of three sections as shown below

The structure of awk program consists of three


sections as shown below

BEGIN{.}
PROGRAME
STATEMENTS
DESIGN

BEGIN section is used for initializing the variables.


$ awk BEGIN { FS = : }

FS is the Field Separator


END section is executed once all the inputs are
processed.
$ awk END { print NR }
NR is the Number of Records
BODY section includes one or more program
statements.
awk commands are statements, which is substituted
for the action part.
The awk command can include variable assignments,
function calls, calculations or any combination of
these.

Print command is used to output


text.
{ print } displays the contents of the
current line.
{ print $1} displays the first field of
the current line.
{ print $1, $5} displays the first field
and fifth field of the current line,

Example with awk command:


1.create a file std_marks with cat
command as follows
$ cat > std_marks
001 Aarya 78
002 Chaitra 85
003 kishore 67
004 Naveen 63
005 Radha 89
(ctrl+d) save and exit

$ awk { print $1, $2 } std_marks


001 Aarya
002 Chaitra
003 kishore
004 Naveen
005 Radha
On execution of the above command,
the first two fields are displayed

awk $3> 70{ print $1, $2, $3 }


std_marks
001 Aarya 78
002 Chaitra 85
005 Radha 89

Create another file marks as


follows:
$ cat > marks
Raghu 78 65 86
Yatish 45 57 62
(ctrl+d)
$ awk { print $1, $2 + $3 + $4}
marks
Raghu 229
Yatish 164

S-ar putea să vă placă și