| Linux Know-How provides a collection of introductory texts on often needed Linux skills. |
|

Home Bash Guide for Beginners The GNU stream editor Interactive editing |
||||||||||||||||||
| See also: SED Commands | ||||||||||||||||||
|
||||||||||||||||||
|
Interactive editingPrinting lines containing a patternThis is something you can do with grep, of course, but you can't do a "find and replace" using that command. This is just to get you started. This is our example text file:
We want sed to find all the lines containing our search pattern, in this case "erors". We use the p to obtain the result:
As you notice, sed prints the entire file, but the lines containing the search string are printed twice. This is not what we want. In order to only print those lines matching our pattern, use the -n option:
Deleting lines of input containing a patternWe use the same example text file. Now we only want to see the lines not containing the search string:
The d command results in excluding lines from being displayed. Matching lines starting with a given pattern and ending in a second pattern are showed like this:
Ranges of linesThis time we want to take out the lines containing the errors. In the example these are lines 2 to 4. Specify this range to address, together with the d command:
To print the file starting from a certain line until the end of the file, use a command similar to this:
This only prints the first two lines of the example file. The following command prints the first line containing the pattern "a text", up to and including the next line containing the pattern "a line":
Find and replace with sedIn the example file, we will now search and replace the errors instead of only (de)selecting the lines containing the search string.
As you can see, this is not exactly the desired effect: in line 4, only the first occurrence of the search string has been replaced, and there is still an 'eror' left. Use the g command to indicate to sed that it should examine the entire line instead of stopping at the first occurrence of your string:
To insert a string at the beginning of each line of a file, for instance for quoting:
Insert some string at the end of each line:
Multiple find and replace commands are separated with individual -e options:
Keep in mind that by default sed prints its results to the standard output, most likely your terminal window. If you want to save the output to a file, redirect it: sed option 'some/expression' file_to_process > sed_output_in_a_file
|
||||||||||||||||||
Home Bash Guide for Beginners The GNU stream editor Interactive editing |
||||||||||||||||||