Shell Practice: Introduction to the sed stream editor
|
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).
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.
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.
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.
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).
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
Pages: 6
(incl. VAT)