Skip to content

Instantly share code, notes, and snippets.

@tankibaj
Last active September 16, 2021 15:29
Show Gist options
  • Save tankibaj/0045dd5ae42cee65a10907ffc185ed1a to your computer and use it in GitHub Desktop.
Save tankibaj/0045dd5ae42cee65a10907ffc185ed1a to your computer and use it in GitHub Desktop.

Remove empty line from file

sed -i '/^\s*$/d' data.txt

OR

sed -i '/^$/d' textfile

Remove ; (symbol) line from file

sed -i '/^\s*;/d' data.txt

Remove # (symbol) line from file

sudo sed -i 's/#.*$//;/^$/d' /etc/libvirt/qemu.conf

Append text brefore first line

sed -i -e '1iTEXTTOSTART' data.txt

Append text after end line

sed -i -e '$aTEXTTOEND' data.txt

Replace line from file

sed -i 's/Find/Replace/g' data.txt

Explanation:

sed = Stream EDitor

-i = in-place (i.e. save back to the original file) The command string:

s = the substitute command

original = a regular expression describing the word to replace (or just the word itself)

new = the text to replace it with

g = global (i.e. replace all and not just the first occurrence)

file.txt = the file name

If you want to find and replace a string that contains the delimiter character (/) you’ll need to use the backslash (\) to escape the slash. For example to replace /bin/bash with /usr/bin/zsh you would use

sed -i 's/\/bin\/bash/\/usr\/bin\/zsh/g' file.txt

The easier and much more readable option is to use another delimiter character. Most people use the vertical bar (|) or colon (:) but you can use any other character:

sed -i 's|/bin/bash|/usr/bin/zsh|g' file.txt
sed -i 's|PermitRootLogin.*|PermitRootLogin no|g' /etc/ssh/sshd_config
sudo sed -i 's|user.*|user = "'$USER'"|g' /etc/libvirt/qemu.conf

Find and Replace

grep -q '^option' file && sed -i 's/^option.*/option=value/' file || echo 'option=value' >> file
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment