SED command tutorial.

sed is an editor which can be used to modify files directly from the command line. It is a stream editor.
Suppose you have a file called a.txt
$ cat a.txt
We wish to replace all instances of the word old with new.
$ sed s'/old/new/' b.txt
$ cat b.txt
File a.txt is copied to b.txt and all instances of the word old are replace with new.
Often it is a good idea to test your expression before actually implementing it. For example:
$ echo older | sed 's/old/new/'
In this example, we tested the command s/old/new/ on the word older. As expected the result is the word 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:
$ echo boot | sed s'/[A-Za-z]*/&s/'
$ echo king | sed s'/[A-Za-z]*/&s/'
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.

No comments:

Post a Comment