Shell Practice: Introduction to the sed stream editor

Slashdot it! Delicious Share on Facebook Tweet! Digg!

Script Files sed

The script file should have a single line for each statement. For example:

s/Gans//
s/jo/Jo/g

The instructions remove the word "Gans" – rather, it substitutes "nothing" for the word, but only for the first instance of the search string. The second lines substitutes "Jo" for "jo" for all instances because of the g option.

To create an executable sed script, include the shebang (#! ) interpreter statement on the first line:

#!/bin/sed -f

If you make the script executable (e.g., chmod 700 [SCRIPTNAME] ), you can call it like any other program. You wouldn't normally use this option. Rather, you would put sed and any script file calls in a shell script. In some cases, the order of the commands matters. Test your scripts before making them "real" to avoid errors and data loss.

Sample Data

You can use the textdata.txt file in Listing 1 to exercise your sed skills. This file looks as though it has been thrown together and contains empty lines, typos, and other errors. The second sample file I'll use in this article is called testlist.txt (Listing 2) and has dates formatted in different ways as content.

Listing 1

textdata.txt

chris hemsworth - Thor 0885465468798746
Scarlett Johansson - Black Widow 08755466584
Robert Downey - Iron Man 0987654321
Mark Ruffalo - Hulk 0405458765143321
Chris Evans - Captain America 0548/9988776655
Jeremy renner - Hawkeye 555/8812470
Tom Hiddleston  - Loki 87841487014848
Samuel Jackson - Nick Fury 043/956026386
Cobie Smulders - Maria Hill 23514560145
Hugh jackman - Wolverine 801539193Paul Rudd - Ant Man 497349000

Listing 2

testlist.txt

22 April 1984
 7.04.1985
30 March 1986
19 April 1987
03.04.1988
26 March 1989
15 April 1990
31-March-1991
19 April 1992
11 April 1993
 3 April 1994
16. April 1995
 7 April 1996
30 March 1997
12 April 1998

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