intumwa intumwa - 1 month ago 18
Bash Question

sed replace anything after nth occurence

I am new in Bash scripting and have been searching for a proper answer to how can I use sed to replace anything after the nth occurence (not to replace the nth occurence).

For example, if I want to change anything that comes after the 2nd space, I'd have the following sentence as input:

Today is a good day
and the following sentence as result:
Today is a friday

Any ideas?


You can use:

s='Today is a good day'
echo "$s" | sed 's/^\(\([^[:space:]]\+[[:space:]]\+\)\{3\}\)[^[:space:]]\+[[:space:]]\+/\1fri/'
Today is a friday

Simplified using -r:

cho "$s" | sed -r 's/^((\S+\s+){3})\S+\s+/\1fri/'
Today is a friday