sed
Important note: sed
uses Basic Regular Expressions (BRE), not Extended Regulars Expressions (ERE). In case you want ERE, use -r
or --regexp-extended
. In most of my exemple, I mainly use BRE. Thus, for groups, you need to use \(...\)
, for optional presence \?
, etc.
Remove specific char from string
# only first occurrence
echo "hell" | sed 's/l//'
hel
# all occurrences ('g' option)
echo "hell" | sed 's/l//g'
he
Replace group matching
echo -e "import \"toto.proto\";\nunrelated line" | sed "s/\(import \"\)\(.*\.proto\)\(.*\)/\1prefix\/\2\3/"
import "prefix/toto.proto";
unrelated line
Print lines between two matching patterns
sed -n '/^pattern1/,${p;/^pattern2/q}'
Remove empty lines
sed '/^$/d'
Only print match
sed -n "s/version=[\"']\(.*\)[\"']/\1/p" setup.py