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.

Figure 2: Searching for uppercase (Man) or lowercase (man).
Figure 21: Adding lines.

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
Figure 22: Handling variables in Bash scripts.

Conclusion

With sed, you can execute complex text manipulation commands without intervention. Its cryptic syntax encourages building scripts one bit at a time.

The Author

Harald Zisler has focused on FreeBSD and Linux since the early 1990s. He is the author of various articles and books on engineering and IT topics.

Buy this article as PDF

Express-Checkout as PDF
Price $2.95
(incl. VAT)

Buy ADMIN Magazine

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

US / Canada

Get it on Google Play

UK / Australia

Related content

comments powered by Disqus
Subscribe to our ADMIN Newsletters
Subscribe to our Linux Newsletters
Find Linux and Open Source Jobs



Support Our Work

ADMIN content is made possible with support from readers like you. Please consider contributing when you've found an article to be beneficial.

Learn More”>
	</a>

<hr>		    
			</div>
		    		</div>

		<div class=