Table of Contents

Linux Commands Cheat Sheet

sed - How to use sed Command in Linux



man sed

NAME
       sed - stream editor for filtering and transforming text


       -e script, --expression=script
              add the script to the commands to be executed

       -i[SUFFIX], --in-place[=SUFFIX]
              edit files in place (makes backup if SUFFIX supplied)


sed Examples

sed -i 's/string1/string2/g' test.txt
sed -i 's/string1/string2/g' *.txt
sed -i 's/string1/string2/g' ./*

sed -i 's#string1#string2#g' test.txt
sed -i "s#string1#string2#g" test.txt
sed -i.bak 's/string1/string2/g' *.conf
sed -i.bak 's/string1/string2/g' ./*
find ./ -name '*.php' -exec sed -i 's/TYPO/TYPE/g' {} \;
sed -i  "s/IPADDR=192.168.0.10/IPADDR=192.168.0.11/g"  ifcfg-eth0 
cat input.txt | sed -e 's/xxx/XXX/g' > output.txt
sed -e 's/xxx/XXX/g' input.txt > output.txt
sed -e '
  s/A/a/g
  s/C/c/g
  s/G/g/g
  s/T/t/g' input.txt
sed -f sample.sed input.txt
Change CR + LF to LF
sed -i -e 's/\r//g' input.txt
Replace with multiple conditions
sed -e 's/AAA/BBB/g' -e 's/CCC/DDD/g' input.txt
Convert tabs to spaces
sed -e 's/<tab>/<space>/g'


Add

Add a string at the beginning of a line
sed -e "s/^/text/"
Add a string at the end of the line
sed -e "s/\$/text/"


Delete, Remove

Delete comment lines starting with #
sed '/^#/d' input.txt
Delete blank lines
sed '/^$/d' input.txt
Remove whitespace at the beginning of a line
sed -e 's/^[<space><tab>]*//'
Remove whitespace at the end of line
sed -e 's/[<space><tab>]*$//'