I know you said "using sed" but if you ever have to do something like this in the real world, here's how using any awk in any shell on every Unix box and doing a full-word string comparison (see how-do-i-find-the-text-that-matches-a-pattern for why that matters):
$ awk -v n=4 '{
for (i=1;i<=NF;i++) {
if ( ($i == "world") && (++cnt == n) ) {
$i = "hello " $i
}
}
print
}' file
world world
world hello world
world world
Imagine your input was:
$ cat file
google.com mygoole.comedy
googleycom google.com
google.com google.com
and you wanted to put "hello" before the 4th google.com
(which is now the last one in the input). With the above awk script you just change $i=="world"
to $i=="google.com"
:
$ cat file
awk -v n=4 '{
for (i=1;i<=NF;i++) {
if ( ($i == "google.com") && (++cnt == n) ) {
$i = "hello " $i
}
}
print
}' file
google.com mygoole.comedy
googleycom google.com
google.com hello google.com
Now try to do the same with a sed script (especially if you only use POSIX syntax and no GNU extensions). Now try using in&out
as the replacement text instead of hello
and you'll find more problems with the sed script.
perl
andawk
from your Linux system without breaking it. – Kusalananda Jan 16 '22 at 12:36busybox
? because most installations ofbusybox
have a minimal-but-adequate version ofawk
built-in. – cas Jan 16 '22 at 12:59