230_sed_lecture09
230_sed_lecture09
1
Slides evolved from previous versions by Hussam Abu-Libdeh and David Slater
Instructor: Bruno Abrahao CS2043 - Unix Tools & Scripting
The Stream Editor
sed
We will use sed as a stream editor, but it is a completely
programming language!
Stream Editor
sed [options] [script] [file]
Stream editor for filtering and transforming text
We will focus on sed ’s/<regexp>/<text>’ [file]
This form replaces anything that matches <regexp> with
<text>.
sed goes line by line searching for the regular expression.
Example:
Example
sed ’/[Dd]avid/d’ filename > filename2
deletes all lines that contain either David or david and saves
the file as filename2.
sed ’s/[[:alpha:]]\{1,3\}[[:digit:]]*@cornell\.edu//g’
Question: what does this do?
$ echo filename1
a b col d e f lapse h i j k lapse m n
$ sed ’s/col.*lapse/collapse/g’ filename1
a b collapse m n
$ echo filename2
a b c col d e f col g h i lapse
sed ’s/col.*lapse/collapse/g’ filename2
a b c collapse
Example:
sed ’s/[[:alnum:]]//g’ Frankenstein.txt
Let’s strip the directory prefix from our pathnames (i.e. convert
/usr/local/src to src)
Example:
pwd | sed ’s/.*\///’
Translates anything preceding (and including) a frontslash to
nothing
Note the backslash-escaped frontslash
Example
Create a new text file named trim.sed
#! /usr/bin/sed -f
s/^ *//
s/ *$//
You can run this script from the shell like any other program:
echo " this is a test " | ./trim.sed
this is a test
We now have a script that trims leading and trailing whitespace!
Instructor: Bruno Abrahao CS2043 - Unix Tools & Scripting
sed in Vim
Replace
Replace pattern matched with regexp with string:
:%s/regexp/string/[options]
http://aurelio.net/soft/sedarkanoid/
http://www.grymoire.com/Unix/Sed.html
cron
cron is a program that enables unix users to execute commands or
scripts automatically at a specified date/time
cron is a daemon, which means it only needs to be started
once and will lay dormant until it is required
On most Linux distributions is automatically installed and
entered into the start up scripts so you don’t have to start it
manually:
Check by tying ps -e | grep cron
Depending on your system, it may show up as cron or crond
We can control the cron daemon in a few di↵erent ways...
If you have a look in your /etc directory you will find sub
directories called
cron.hourly
cron.daily
cron.weekly
cron.monthly
SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
crontab
Syntax:
a. b. c. d. e. command to be executed
a. min (0-59)
b. hour (0-23)
c. day of month (1-31)
d. month (1-12)
e. day of week (0-6) (Sunday = 0)