This unix and linux site aims to provide book reviews and free ebook on unix linux, unix commands, unix shell, unix programming, unix shell scripting, unix tutorial, suse linux, rehat linux, debian linux, slackware linux, linux server, linux commands, fedora linux, linux gui, linux networking, unix time sharing concepts, programming linux games, samba-3, motif programming, unix signal programming, and linux complete reference, etc

Sed by example, Part 2

Get to know the powerful UNIX editor
By Daniel Robbins
Sed is a very powerful and compact text stream editor. In this article, the second in the series, Daniel shows you how to use sed to perform string substitution; create larger sed scripts; and use sed's append, insert, and change line commands
Sed is a very useful (but often forgotten) UNIX stream editor. It's ideal for batch-editing files or for creating shell scripts to modify existing files in powerful ways. This article builds on my previous article introducing sed.
Substitution!
Let's look at one of sed's most useful commands, the substitution command. Using it, we can replace a particular string or matched regular expression with another string. Here's an example of the most basic use of this command:
$ sed -e 's/foo/bar/' myfile.txt
The above command will output the contents of myfile.txt to stdout, with the first occurrence of 'foo' (if any) on each line replaced with the string 'bar'. Please note that I said first occurrence on each line, though this is normally not what you want. Normally, when I do a string replacement, I want to perform it globally. That is, I want to replace all occurrences on every line, as follows:
$ sed -e 's/foo/bar/g' myfile.txt
The additional 'g' option after the last slash tells sed to perform a global replace.
Here are a few other things you should know about the 's///' substitution command. First, it is a command, and a command only; there are no addresses specified in any of the above examples. This means that the 's///' command can also be used with addresses to control what lines it will be applied to, as follows:
$ sed -e '1,10s/enchantment/entrapment/g' myfile2.txt
The above example will cause all occurrences of the phrase 'enchantment' to be replaced with the phrase 'entrapment', but only on lines one through ten, inclusive.

Popular Posts

Linux Unix Books