Chinaunix首页 | 论坛 | 博客
  • 博客访问: 362567
  • 博文数量: 157
  • 博客积分: 3001
  • 博客等级: 中校
  • 技术积分: 1330
  • 用 户 组: 普通用户
  • 注册时间: 2008-11-06 13:47
文章分类

全部博文(157)

文章存档

2011年(1)

2010年(28)

2009年(124)

2008年(4)

我的朋友

分类: LINUX

2010-04-21 09:36:41

You can use the sed command to change all occurrences of one string to another within a file, just like the search-and-replace feature of your word processor. The sed command can also delete a range of lines from a file. Since sed is a stream editor, it takes the file given as input, and sends the output to the screen, unless you redirect output to a file. In other words, sed does not change the input file.

The general forms of the sed command are as follows:

Substitution sed 's/<oldstring>/<newstri ng>/g' <file>
Deletion sed '<start>,<end>d' < file>

Let's start with a substitution example. If you want to change all occurrences of lamb to ham in the poem.txt file in the grep example, enter this:

sed 's/lamb/ham/g' poem.txt
Mary had a little ham
Mary fried a lot of spam
Jack ate a Spam sandwich
Jill had a ham spamwich

In the quoted string, the "s" means substitute, and the "g" means make a global change. You can also leave off the "g" (to change only the first occurrence on each line) or specify a number instead (to change the first n occurrences on each line).

Now let's try an example involving deletion of lines. The values for start and end can be either a line number or a pattern to match. All lines from the start line to the end line are removed from the output. This example will delete starting at line 2, up to and including line 3:

sed '2,3d' poem.txt
Mary had a little lamb
Jill had a lamb spamwich

This example will delete starting at line 1, up to and including the next line containing Jack:

sed '1,/Jack/d' poem.txt
Jill had a lamb spamwich

The most common use of sed is to change one string of text to another string of text. But I should mention that the strings that sed uses for search and delete are actually regular expressions. This means you can use pattern matching, just as with grep. Although you'll probably never need to do anything like this, here's an example anyway. To change any occurrences of lamb at the end of a line to ham, and save the results in a new file, enter this:

sed 's/lamb$/ham/g' poem.txt > new.file

Since we directed output to a file, sed didn't print anything on the screen. If you look at the contents of new.file it will show these lines:

Mary had a little ham
Mary fried a lot of spam
Jack ate a Spam sandwich
Jill had a lamb spamwich

Use the man sed command for more information on using sed.

For more information on the sed command, see the .

阅读(555) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~