Reputation: 354
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?
Upvotes: 4
Views: 2754
Reputation: 41460
Why not just use awk
echo "Today is a good day" | awk '{print $1,$2,"a friday"}'
Today is a friday
This will keep the first two fields, and replace the rest of the line.
Upvotes: 1
Reputation: 1
As I understand the question being asked, this doesn't really even need sed or awk, if you're using Unix 7th Edition shell or a newer shell based on it like sh or bash. Just use an unfortunately obscure feature of the set command:
$ set Today is a good day
$ echo $1 $2 "Friday"
Today is Friday
The original question asked about patterns, but the example offered has the pattern being just a single space. The second occurrence of the space implicitly follows the second argument. You can adapt it to "nth occurrence" using a little shell arithmetic, I imagine.
This set trick has been around a long time, even though I just recently discovered it. An example of its use appears on page 136 of Kernighan and Pike's "The UNIX Programming Environment" (1984). It works the same on Bash, and I would guess it must be present on any 7th Ed. shell derivative.
Upvotes: 0
Reputation: 786289
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
Upvotes: 2
Reputation: 44073
I would say
echo 'Today is a good day.' | sed 's/ /&\n/3; s/\n.*/friday/'
This consists of two commmands:
s/ /&\n/3 # inserts a \n after the third space
s/\n.*/friday/ # replaces \n and everything that comes after it with "friday"
This uses the fact that \n
will never appear in a line -- something that makes \n
great as a marker in sed scripts. &
refers to the matched portion of the line.
Upvotes: 0