e9133e1d
e9133e1d

Reputation: 13

How can I search and replace for two characters with a string in between and only replace the latter character using sed?

Take the following string, for example:

some random text*
- sed is actually not that easy.*
other text

How can I search for lines containing both - and *, then replace the asterisk in that line with a string?

(For Example) Using the string "test" to replace the asterik in matched lines, the output would look this:

some random text*
- sed is actually not that easy.test
other text

I tried

sed -i '' 's/\- .*\*/\n\n:::\n/g';

But the problem with that is that it replaces the whole line, instead of just the asterisk.

Upvotes: 1

Views: 52

Answers (1)

The fourth bird
The fourth bird

Reputation: 163342

If you want to match and keep the hyphen at the start of the line, and replace the asterix at the end of the line, you can use a capture group \(...\) for what you want to keep and use that group in the replacement with \1

sed -i 's/^\(- .*\)\*$/\1test/' file

The contents of file will be:

some random text*
- sed is actually not that easy.test
other text

If the characters are not directly at the start or end of the string, you can remove the anchors ^ and $

Upvotes: 2

Related Questions