The slash as a delimiter
The character after the s is the delimiter. It is conventionally a slash, because this is what ed, more, and vi use. It can be anything you want, however. If you want to change a pathname that contains a slash - say /usr/local/bin to /common/bin - you could use the backslash to quote the slash:- sed 's/\/usr\/local\/bin/\/common\/bin/'
new
- sed 's_/usr/local/bin_/common/bin_'
new
- sed 's:/usr/local/bin:/common/bin:'
new
- sed 's|/usr/local/bin|/common/bin|'
new
Using & as the matched string
Sometimes you want to search for a pattern and add some characters, like parenthesis, around or near the pattern you found. It is easy to do this if you are looking for a particular string:- sed 's/abc/(abc)/'
new
The solution requires the special character "&." It corresponds to the pattern found.
- sed 's/[a-z]*/(&)/'
new
- % echo "123 abc" | sed 's/[0-9]*/& &/' 123 123 abc
- % echo "123 abc" | sed 's/[0-9][0-9]*/& &/' 123 123 abc
Using \1 to keep part of the pattern
I have already described the use of "(" ")" and "1" in my tutorial on regular expressions.To review, the escaped parentheses (that is, parentheses with backslashes before them) remember portions of the regular expression. You can use this to exclude part of the regular expression. The "\1" is the first remembered pattern, and the "\2" is the second remembered pattern. Sed has up to nine remembered patterns.If you wanted to keep the first word of a line, and delete the rest of the line, mark the important part with the parenthesis:
- sed 's/\([a-z]*\).*/\1/'
- echo abcd123 | sed 's/\([a-z]*\).*/\1/'
If you want to switch two words around, you can remember two patterns and change the order around:
- sed 's/\([a-z]*\) \([a-z]*\)/\2 \1/'
The "\1" doesn't have to be in the replacement string (in the right hand side). It can be in the pattern you are searching for (in the left hand side). If you want to eliminate duplicated words, you can try:
- sed 's/\([a-z]*\) \1/\1/'
your
ReplyDeletesed 's/\([a-z]*\) \([a-z]*\)/\2 \1/'
example did not work for me.
it just returned the original string.