sed and awk
Sed
• Sed is a multipurpose command which performs the work of several
filters
• Sed is non interative stream editor.
• Sed Syntax:
# sed options ‘address action’ file
Sed syntax
# sed options ‘address action’ input_file
By line number
By pattern match
Single-Line address
Range Address
Single Pattern address
Range Pattern Address
Single-Line address
• Specifies only one line in the input file
Examples:
• show only line 4
#sed ‘4q' input-file
• show only last line
#sed ‘$p’/proc/cpuinfo
• Observe what happens? Last line is printed two times.
• Always use –n option to suppress duplicate printing.
• substitute “endif” with “fi” on line 10
#sed ‘10 s/endif/fi/’ input-file
Range Address (between two line numbers)
• Prints line between specified line numbers
Examples:
• Sed –n ‘1,10p’ /proc/cpuinfo
Single Pattern match address
• use regular expression to match lines
• written between two slashes
• process only lines that match
• may match several lines
• lines may or may not be consecutives
Examples:
• sed ‘/processor/s/:/::/’ /proc/cpuinfo
Range Pattern match address
• Prints line between two springs.
Sed –n ‘/pattern1/,/pattern2/p’ input_file
address1 address2
• Line between pattern1 and pattern2 are printed
Address with ! (print not of)
• Address with an exclamation point (!) instruction will be applied to all
lines that do not match the address
Example:
print lines that do not contain “obsolete”
sed -e ‘/obsolete/!p’ input-file
Sed options
Example
sed –e ‘1,2p’ –e ‘6,8’ –e ‘$ p’ file_name
sed –i ‘1,2p’ –e ‘6,8’ –e ‘$ p’ file_name
Sed commands
Line Number
• line number command (=) writes the current line number before each
matched/output line
Examples:
• sed '/processor/=' /proc/cpuinfo
• Now try and observe the diffrence:
• sed -n '/processor/=' /proc/cpuinfo
Modify Commands
Modify Commands
Modify Commands Discription Example
Insert (i) seq 3 | sed '2i hello’
Append (a) Seq 10 | sed ‘2a hello’
Change (c)
Delete (d)
Substitute (s/str1/str2/)