sed -n '10p' myfile.txt
sed '5!/s/foo/bar/' file.txt
sed '/^hello/ s/h/H/' file.txt
s '1,$ s/foo/bar/' file.txt
sed -nr '/^foo/,/^bar/p' file.txt
sed 's_/bin/bash_/bin/sh_' file.txt
sed 's/[a-zA-Z]/& /g' file.txt
sed -r s_[a-z]+.*_\1_' file.txt
sed -r 's_([a-zA-Z]*) ([a-zA-Z]*)_\2 \1_' f1
sed -r 's_([a-z]+) \1_\1_ig' f1
sed -r 's_foo_bar_w replaced.txt' file.txt
sed -e 's_foo_bar_' -e 's_hello_HELLO_' file.txt
#!/bin/bash
sed '
s/a/A/
s/foo/BAR/
s/hello/HELLO/
' <$1
- call with
./myscript.sh myfile.txt
sed -r '/start/,/end/ s/#.*//' file.txt
sed -r '/start/,$ d' file.txt
sed -rn '/start/,/end/ !p' file.txt
sed -r '/start/q' file.txt
sed -r '5 r newfile.txt' file.txt
sed '/foo/ a AFTER FOO' file.txt
sed '/foo/ i BEFORE FOO' file.txt
sed '/foo/c FOO IS CHANGED' file.txt
Nested sed ranges with inversion. Between lines 1,100 apply actions where the pattern DOESN'T match.
#!/bin/bash
sed '
1,100 {
/foo/ !{
s_hello_HELLO_
s_yes_YES
}
}'
- call with
./script.sh <file.txt
Use nested addresses with change, insert and append to modify: the line before match, the line with match, the line after match.
#!/bin/bash
sed '
/^#/ {
i\
#BEFFORE ORIGINAL COMMENt
a\
#AFTER ORIGINAL COMMENT
c\
# ORIGINAL COMMENT IS NOW THIS LINE
}'
Insert new line before the first comment, after the first comment put in the contents of file and quit immediately afterwards
#!/bin/bash
sed '
/^#/ {
i #BEFORE COMMENT
r myotherfile.txt
q
}'
sed 'y/abc/ABC/' file.txt
sed -r '/^#/w comments.txt' file.txt
sed '1~2p' file.txt
sed -i.bak 's/hello/HELLO/' file.txt