Lec 05
Lec 05
Objectives
• Record
– Every line of an input file is a record.
• The current record can be referenced with $0.
• awk operates on one record at a time.
• Field
– A record consists of fields, which by default are
separated by any number of SPACES or TABS.
– Each field is numbered and can be referred to
• $1 is the first field, $2 is the second, etc.
awk Example
• Q1: How to select all the cars which were made after
or during 1991 (column 3) and cost less than $6,250
(column 4)?
• Q2: How to select cars made either by ford, or buick?
Data processing & Arithmetic
• Syntax:
sed ‘command’ file(s)
sed –e ‘command’ –e ‘command’ … file(s)
sed –f scriptfile file(s)
Useful sed Commands
Flags:
n replace nth instance of pattern with replacement
g replace all instances of pattern with replacement
p write to STDOUT if a successful substitution takes
place
w file write to file if a successful substitution takes place
sed Substitute (Contd)
[address1[ , address2]]s/pattern/replacement/[flags]
• An address can be
– a regular expression enclosed by forward slashes
/regex/ , or
– a line number .
• The $ symbol can be used to denote the last line.
• If one address is given, then the substitution is
applied to lines containing that address.
• If two addresses are given separated by a
comma, then the substitution is applied to all
lines between the two lines that match the
pattern.
Questions
• Q5: What does the following command do?
sed 's/Tx/Texas/' foo
cat animal1
The black cat was chased by the brown dog.
The black cat was not chased by the brown dog.
sed -e '/not/s/black/white/g' animal1
sed Delete
• DELETE(d)
[address1[, address2] ]d
• sed 6d foo
– deletes line 6
• Q8: How to delete lines 1-10 from the file
foo
• Q9: How to delete lines 11 through the end
of the file foo
Questions
• Q10: What does the following command do?
sed ‘/^Co*t/,/[0-9]$/d’ foo
• Q11: What is the output of the following
command?
cat linefile
line 1 (one)
line 2 (two)
line 3 (three)
sed -e '/^line.*one/s/line/LINE/' -e '/line/d' linefile
Questions