Skip to content

SED

SED

https://github.com/adrianscheff/useful-sed
https://github.com/chmln/sd easier sed

Replace

Replace Line in file that matches:

sed -i 's/MATCHED_LINE.*/REPLACED_LINE/' test.conf

#Uncomment matched line
sed -i -E 's/#(Color.*)/\1/' /etc/pacman.conf 

#Comment matched line
sed -i -E 's/(Color.*)/#\1/' /etc/pacman.conf 

Remove

Remove the 1st line:

sed 1d filename

Remove the first 100 lines (remove line 1-100):

sed 1,100d filename

Remove lines with string (e.g. 'bbo'):

sed "/bbo/d" filename
# case insensitive:
sed "/bbo/Id" filename

Remove lines whose nth character not equal to a value (e.g. 5th character not equal to 2):

sed -E '/^.{5}[^2]/d'
#aaaa2aaa (you can stay)
#aaaa1aaa (delete!)

Remove empty lines:

sed '/^$/d'

Delete/remove last line:

sed '$d'

Add

Add string to beginning of file (e.g. "["):

sed -i '1s/^/[/' file

Add string at certain line number (e.g. add 'something' to line 1 and line 3):

sed -e '1isomething' -e '3isomething'

Add string to beginning of every line (e.g. 'bbo'):

sed -e 's/^/bbo/' file

Print a number of lines (e.g. line 10th to line 33 rd):

sed -n '10,33p' <filename