« Previous 1 2 3 4
Shell practice: Introduction to the sed stream editor
Quick Edit
Adding and Inserting
You add lines in a file by stating a line number or after (a
) and before (i
) text found with a search pattern (Figure 21). If you enter multiple line numbers or the pattern matches multiple times, the insertion occurs for each instance.
In the first sed command, a new line is added above the first line in the file; in the next command, 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.
Shell Variables
If a shell variable needs to be resolved, you need to enclose the statements in double quotes ("
) instead of single quotes ('
). The short shell script in Listing 3 shows how to handle variables by searching through the sample file and outputting the matching lines. Figure 22 shows the result.
Listing 3
searchString.sh
01 #! /bin/sh 02 echo -n "Enter search string: ";read sstring 03 cat textdata.txt | sed -n "/$sstring/"p
Conclusion
With sed, you can execute complex text manipulation commands without intervention. Its cryptic syntax encourages building scripts one bit at a time.
Infos
- Project page for sed: http://sed.sourceforge.net/
- Text files: ftp://ftp.linux-magazine.com/pub/listings/admin-magazine.com/28
« Previous 1 2 3 4
Buy this article as PDF
(incl. VAT)