Sed - An Introduction and Tutorial by Bruce Barnett
|
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/' Gulp. Some call this a 'Picket Fence' and it's ugly. It is easier to read if you use an underline instead of a slash as a delimiter: sed 's_/usr/local/bin_/common/bin_' Some people use colons: sed 's:/usr/local/bin:/common/bin:' Others use the "|" character. sed 's|/usr/local/bin|/common/bin|' Pick one you like. As long as it's not in the string you are looking for,anything goes. And remember that you need three delimiters. If you get a "Unterminated `s' command" it's because you are missing one of them. 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)/' This won't work if you don't know exactly what you will find. How can you put the string you found in the replacement string if you don't know what it is? The solution requires the special character "&." It corresponds to the pattern found. sed 's/[a-z]*/(&)/' You can have any number of "&" in the replacement string. You could also double a pattern,e.g. the first number of a line: % echo "123 abc" | sed 's/[0-9]*/& &/' 123 123 abc Let me slightly amend this example. Sed will match the first string,and make it as greedy as possible. I'll cover that later. If you don't want it to be so greedy (i.e. limit the matching),you need to put restrictions on the match. The first match for '[0-9]*' is the first character on the line,as this matches zero of more numbers. So if the input was "abc 123" the output would be unchanged (well,except for a space before the letters). A better way to duplicate the number is to make sure it matches a number: % echo "123 abc" | sed 's/[0-9][0-9]*/& &/' 123 123 abc (编辑:网站开发网_马鞍山站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |

