Modifying a File Directly[edit]

Using the above tips, you can modify a file directly by using the -i parameter, with the filename as the second argument:

$ sed -i "s/search/replace/g" /path/to/file

You can also glob multiple files.

$ sed -i -e "s/search/replace/g" files*.txt

Simple search / replace[edit]

Global search and replace:

$ sed 's/<search>/<replace>/g'

To replace only the first match:

$ sed '0,/<search>/s//<replace>/'

Remove HTML tags[edit]

$ sed -e 's/<[^>]*>//g' <file>

Remove File Extensions[edit]

$ sed 's/\(.*\)\..*/\1/'


$ echo "house.txt" | sed 's/\(.*\)\..*/\1/'  # returns 'house'

Delete Matching Line[edit]

$ sed '/someline/d'

Inserting a Line Before/After a Match[edit]

Use: 0,/<regex>/s//<replacement text where \0 is the found line>/

## Add a password line before the first title entry in the grub.conf file.
$ sed -i "0,/^title/s//password --encrypted $Password\n\n\0/" $GrubConfig

To append after, just put \0 before your replacement text.

Another example: To add in a systemd service file:

# lightdm takes responsibility for stopping plymouth, so if it fails
# for any reason, make sure plymouth still stops


Running this will append an 'After' dependency to the service file before the service section.

# sed -i "0,/^\[Service\]/s//\n\n\0/" /usr/lib/systemd/system/lightdm.service

Grap Specific Section using Regex[edit]

To grab a specific section of a string, for instance '3' in 'Server time offset: 3':

$ echo 'Server time offset: 3' | sed -n -e 's/.*: \([0-9]*\)/\1/p'

This can also be done with grep, though it isn't regex:

$ echo 'Server time offset: 3' | /bin/grep -ohE '[0-9]*'

Join Every Other Line[edit]

To join every other line, useful for making key:value pairs, use:

'$!N;s/\n/ /'

Further Reading[edit]