Shell Practice: Introduction to the sed stream editor

Slashdot it! Delicious Share on Facebook Tweet! Digg!

Character Replacement

Use the y option for character filtering and other applications. The pattern should contain all the characters that need to be replaced, and the replacement statement should have the same number of characters. The command structure should only have s , and -n should be omitted:

sed y'/[Search CHAR]/[Replacement CHAR]/'

Substitute the first character of only the lines in textdata.txt that begin with c in lowercase characters with uppercase character C (Figure 17).

Figure 17: One-for-one character replacement.

You use c to replace entire lines:

sed 'PATTERN'c'REPLACEMENT'

You can also do it like this:

sed [LINE(n)] c'REPLACEMENT'

The example in Figure 18 deletes an empty line and replaces it with a series of dashes.

Figure 18: Replacing an entire line matched to a search pattern.

In place of a search pattern, line numbers can be used. Be aware that even if you specify multiple line numbers they will all be replaced by one single instance of the replacement string. So, if you pick three lines, it will seem like the first line gets replaces, and the second and third lines get deleted.

The example in Figure 19 deletes line 2 and substitutes a series of hash marks. The second example deletes through line 4 and replaces them with the given line.

Figure 19: Replacing whole lines per line numbers.

You also can delete lines using the d option and using a search pattern or line numbers:

sed '/PATTERN/'d
sed [LINE(n)]d

Using the commands in Figure 20, you can search and delete an empty line and then delete line 4.

Figure 20: Deleting lines.

Adding and Inserting

With a , you add lines beneath and, using i , you insert a lines above the search pattern. To state where you must insert the line, you indicate the search pattern or a line number. If you enter multiple line numbers or the pattern matches multiple times, the insertion occurs for each instance (Figure 21).

Figure 21: Adding lines.

In the second line, a new line is added above the first line in the file; whereas in the next line, it's added at the end ($ ). The command at the next prompt adds a new line above the matched search pattern, and the next line adds it below.

Buy this article as PDF

Express-Checkout as PDF

Pages: 6

Price $0.99
(incl. VAT)

Buy Ubuntu User

SINGLE ISSUES
 
SUBSCRIPTIONS
 
TABLET & SMARTPHONE APPS
Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content