Using sed to replace a pattern by symbol

2019-08-29 00:15发布

问题:

How do I replace a pattern by looking at sentence symbol by using sed?
Input

this-
-this-

Results I want

start
middle

My code

sed 's/[a-zA-Z]-/start/g'
sed 's/-[a-zA-Z]-/middle/g'

Results I get

abastart

Am I doing something wrong?

回答1:

This should do:

sed -r 's/^[a-zA-Z]+-/start/;s/^-[a-zA-Z]+-/middle/' file
start
middle
  • -r or -E for extended regex
  • + to tell its 1 or more character
  • ^ to tell to start from beginning of line
  • ; to have more than one sed block in one line
  • You can add $ to make sure whole line is matched s/^[a-zA-Z]+-$/start/


标签: linux sed