sed

Table of Contents

1. Remplace last occurence of a character

Remplace the last occurence of # on each line with ;

sed 's/\(.*\)#/\1;/'

2. Append text

Append foo to a new line below pattern

sed '/pattern/a foo'

3. Capitalize letters in a string

Capitalize the first letter of a string

sed -E 's/^(.)/\u\1/'

Capitalize every letters after whitespaces

sed -E 's/ (.)/ \u\1/g'

4. Remove numbers from the end of a line

Remove a space and the ending 5 digits of a string, e.g. This is a line 12345 while result in This is a line

sed 's/\(.*\) [0-9]\{5\}$/\1/'

5. Print matched lines

Only print lines containing https.*channel pattern and remplace any spaces with @

sed -n '/^https.*channel/s/[[:space:]]/@/p' urls

6. Return value between foo and bar on lines starting with baz1 or baz2

# ~/file
baz1 foohellobar
baz2 fooworldbar
baz3 foowaterbar
sed -n '/^baz[12]/s;.*foo\(.*\)bar.*;\1;p' ~/file

7. On the last line of the file $, run list of commands {}

sed -i '${/^$/d}'

8. Delete empty lines at the end of a file

sed -e :a -e '/^\n*$/{$d;N;ba' -e '}'

9. Replace every non alphabetic or numeric characters with an underscore

sed 's/[^[:alnum:]]\+/_/g'

10. Backup file before applying changes using -i.bak

sed -i.bak 's/foo/bar/' file

11. Delete the first 3 lines of file that contains foo

while read -r file
do
    sed -i '1,3d' "$file"
done < <(grep -rl '^foo' ~/dir)

12. Remove every lines not starting with #

sed -i '/^#/!d' file

13. Lowercase every lines

sed -i 's@^.\+$@\L&@' file

14. References