Does Linux Have a Search & Replace Feature?
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 sed manual.
No comments:
Post a Comment