Warm tip: This article is reproduced from stackoverflow.com, please click
sed unix

Substitution from 2nd to 4th occurrence using sed Command

发布于 2020-03-27 15:40:50

enter image description here

I want to substitute the p with "@" from 2nd occurrence to 4th occurrence.

sed 's/p/@/2g' file.txt

This command substitutes from the 2nd occurrence up to the last occurrence of "p". But 1 want to substitute from 2nd to 4th. So how to do it ?

Questioner
mbx20
Viewed
88
oguz ismail 2020-01-31 18:54

Assuming this is bash or zsh, you can make use of brace expansion.

sed -e's/p/@/2'{,,} file

{,,} will repeat -e's/p/@/2' thrice, so it'll replace 2nd, 3rd and 4th ps.