The sed command is very complex and powerful. One of the many things that sed can do is display the contents of a file while searching for a pattern (limited regular expression), and replacing the found pattern with some new data.
One command syntax: sed 's/pattern/new_data/' filename:
- This will display the contents of the file while
- searching for lines with 'pattern' and
- replacing the pattern with 'new_data'.
By default sed acts on only the first occurrence of a matched pattern. The pattern is a limited regular expression.
- Example: sed 's/dog/cat/' file1
- This example displays all the lines of file1 with the first occurrence of 'dog' on any line changed to 'cat'.
NOTE:
- The file is not being changed.
- Sed is not effected by the LC_COLLATE setting.
Examples
Among the many things that sed (the stream editor) can do is perform editing functions in the stream, using regular expressions.
- Add g for global replacements (all occurrences of the string per line). (Cobbault, pp. 131)
- Add - n: character indicating no display of file content.
sed -n '2,5p' file1
sed '4,7s/abc/ABC/g' file1
- Displays entire file with lines 4-7 modified.
sed '/abc/d' file1
- Displays all lines that don't have "abc"
An ampersand (&) can be used in the second part to recall the matched pattern.
sed 's/abc/***&***/' files
- Displays the content of file1 with three stars before and after the first "abc" on the line.
- Note: The ampersand (&) is not a regular expression character, but rather a feature of the 'sed s' command.
sed 's/Hello/(&)/' file1
- Displays the content of file1 with parenthesis around the first "Hello" on each line.
sed 's/Hello/(&)/g' file1
- Displays the content of file1 with parenthesis around every "Hello" on every line.