Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS 497C – Introduction to UNIX Lecture 30: - Filters Using Regular Expressions – grep and sed Chin-Chih Chang

Similar presentations


Presentation on theme: "CS 497C – Introduction to UNIX Lecture 30: - Filters Using Regular Expressions – grep and sed Chin-Chih Chang"— Presentation transcript:

1 CS 497C – Introduction to UNIX Lecture 30: - Filters Using Regular Expressions – grep and sed Chin-Chih Chang chang@cs.twsu.edu chang@cs.twsu.edu

2 Line Addressing To overcome the problem of printing duplicate lines, you should use the -n option whenever you use the p command. $ sed -n ‘1,2p’ emp.lst $ sed –n ‘$p’ emp.lst To reverse line selection criteria, use !. $ sed -n ‘3,$!p’ emp.lst To select lines from the middle, do as: sed -n ‘9,11p’ emp.lst

3 Line Addressing You can select multiple sections as follows: $ sed -n -e ‘1,2p’ -e ‘7,9p’ -e ‘$p’ emp.lst The second form of addressing lets you specify a pattern (or two) rather than line numbers. This is known as context addressing where the pattern has a / on either side. You can locate the senders in your mailbox: sed -n '/From: /p' /var/mail/cs497c

4 Context Addressing sed –n ‘/^From: /p’ /var/mail/cs497c sed –n ‘/wilco[cx]k*s*/p’ emp.lst You can also specify a comma-separated pair of context address to select a group of contiguous lines: sed –n ‘/johnson/,/lightfoot/p’ emp.lst To list files which have written permission for the group: ls –l | sed –n ‘/^…..w/p’

5 Editing Text Apart from selecting lines, sed can edit text itself. Like vi, sed uses the i (insert), a (append), c (change) and r (read) commands in similar manner. Use the a command and have a \ at the end of each line except the last one.You can append two lines in this way: $ sed ‘$a\ > # Place this line at the end’ wwwlib.pl > $$

6 Editing Text You can use the following command to insert the blank line before every line: sed ‘i\ ‘ foo In C Shell, this needs to be done in this way: sed ‘i\\ \ ‘ foo

7 Editing Text The r (read) command lets you read in a file at a certain location of the file. sed ‘/ /r template.html’ form_entry.html The d (delete) command removes lines. sed ‘/^#/d’ foo > bar The w (write) command writes the selected lines to a separate file. sed ‘/ /,/ /w forms.html’ *.html


Download ppt "CS 497C – Introduction to UNIX Lecture 30: - Filters Using Regular Expressions – grep and sed Chin-Chih Chang"

Similar presentations


Ads by Google