> For the complete documentation index, see [llms.txt](https://abhav.gitbook.io/linux-tutorials/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://abhav.gitbook.io/linux-tutorials/sed.md).

# sed

stream editor

Can perform lots of functions on file like searching, find and replace, insertion or deletion.

```
sed 's/<search_word>/<replace_word>/<options>' filename
```

Here the “s” specifies the substitution operation. The “/” are delimiters. The “search\_word” is the search pattern and the “replace\_word” is the replacement string.

***Note - By default, the sed command replaces the first occurrence of the pattern in each line and it won’t replace the second, third…occurrence in the line.***

1. **Replacing or substituting string**&#x20;

```sh
sed 's/unix/linux/' file.txt
```

replaces the first occurance of `unix` in every line.

2. **Replacing the nth occurrence of a pattern in a line**

```sh
sed 's/unix/linux/2' file.txt
```

Use the /1, /2 etc flags to replace the first, second occurrence of a pattern in a line. The above command replaces the second occurrence of the word “unix” with “linux” in a line.

3. **Replacing all the occurrence of the pattern in a line**

```bash
sed 's/unix/linux/g' file.txt
```

4. **Replacing from nth occurrence to all occurrences in a line**

```bash
sed 's/unix/linux/3g' file.txt
```

5. **Replacing string on a specific line number**

```bash
sed '3 s/unix/linux/' file.txt
```

6. **Duplicating the replaced line with /p flag**

```bash
sed 's/unix/linux/p' file.txt
```

The /p print flag prints the replaced line twice on the terminal. If a line does not have the search pattern and is not replaced, then the /p prints that line only once.

7. **Printing only the replaced lines**

```bash
sed -n 's/unix/linux/p' file.txt
```

Use the -n option along with the /p print flag to display only the replaced lines. Here the -n option suppresses the duplicate rows generated by the /p flag and prints the replaced lines only one time.

8. **Replacing string on a range of lines**&#x20;

You can specify a range of line numbers to the sed command for replacing a string.

```bash
sed '1,3 s/unix/linux/' file.txt
```

```bash
sed '2,$ s/unix/linux/' file.txt
```

Here the `$` represents the last line

9. **Deleting lines from a particular file**

```bash
sed '5d' filename.txt
```

Deletes the 5th line from starting

To delete last line ->

```bash
sed '$d' filename.txt
```

10. **To Delete line from range x to y**

```bash
sed '3,6d' filename.txt
```

Deletes from 3rd to 6th line

To delete from nth to last line ->

```bash
sed '3,$d' filename.txt
```

11. **To Delete pattern matching line**

```bash
sed '/pattern/d' filename.txt
```
