In bash scripting, if you want to edit some file from command line, then you can use sed. 10 Basic examples that I’ve provided here, you’ll find using command line more enjoyable and fun.

About SED

sed is an Non-interactive stream editor.

Features

Usage

sed [ Options ] ' instruction ' file     | PIPE | STDIN

Some examples

1. Print line no. from file (it will print line 1 to 5 .)

sed -n '1,5p' filename

2. Print lines except 1 to 6 line.

sed -n '1,6!p'  filename

3. Print below two lines from matches word

sed -ne '/word/,+2p' filename

4. Delete two lines with matches word

sed -e '/word/,+2d' filename

5. Delete below 2 lines from match word

sed -e '/5/{n;N;d}' filename

6. search two words

sed -ne '/monkey/,/donkey/p' filename

7. delete blank file (-i = edit source file and backup sourch file (filename.bak))

sed -i.bak '/^$/d' filename

8. delete second line after first line

sed -ne '1~2p'  filename

9. Search and Replace

g = Global s = search I = incasecensitive

sed -e 's/find/replace/g' filename

10. Multiple instruction

it will delete blank lines then search RAM and replace SHYAM (only print not change in source file )

sed -e '/^$/d' -e 's/RAM/SHYAM/g' filename

or

sed -e '/^$/d' ; 's/RAM/SHYAM/g' filename

the line contain “NAME” in the same line search RAM and replace SHYAM.

sed -e '/NAME/s/RAM/SHYAM/g' filename