Substitution
Suppose you have a file called a.txt
We wish to replace all instances of the word old with new.$ cat a.txt old older oldest
File a.txt is copied to b.txt and all instances of the word old are replace with new.$ sed s'/old/new/'b.txt $ cat b.txt new newer newest
Often it is a good idea to test your expression before actually implementing it. For example:
In this example, we tested the command s/old/new/ on the word older. As expected the result is the word newer.$ echo older | sed 's/old/new/' newer
The backslash character '\' is used to escape special characters. For example, and address data/input.txt would create confusion insides the substitution function s/// due to the extra slash. To remedy this you type data/input.txt as data\/input.txt.
The ampersand '&' character is refers to the matched string. For example:
This code converts singular nouns to plurals by adding s. [A-Za-z] matches an English letter in both capital and small case. The * character means 1 or more. So we are matching a string with one or more English characters in either case. & refers to the matched word. &s suffixes an s to the matched word.$ echo boot | sed s'/[A-Za-z]*/&s/' boots $ echo king | sed s'/[A-Za-z]*/&s/' kings
No comments:
Post a Comment