mora mora - 6 days ago 5
Bash Question

How to remove the N th target word(='remove_mark') in a line by sed?

I am learning sed of shell.
I tried the following code,

echo "one tworemove_markthree fourremove_markfive" | sed -E "s?(.*)remove_mark(.*)?\1\2?"


I expected the output of this is

one twothree fourremove_markfive


But the output of above code is following,

one tworemove_markthree fourfive


The first remove_mark is remained but the second one is removed.
However I would like to remove the first one. How to do it? And How to removed all of matched target word? Thank you very much.

Answer

By just matching remove_mark and replacing with nothing.

Example

$ echo "one tworemove_markthree fourremove_markfive" | sed 's/remove_mark//'
one twothree fourremove_markfive

To remove all the targets, use g(global) modifier.

Example

$ echo "one tworemove_markthree fourremove_markfive" | sed 's/remove_mark//g'
one twothree fourfive