Replace x Number of String Occurrence with Sed

Ok,

So I have a huge file that has over 12000 lines in it.

in this file, there are 589 occurrences of the string "use five-minute-interval" spread in various areas in the file.

How can i replace the the last 250 of the occurrences of "use five-minute-interval" with "use four-minute-interval"?

this is as far as i got:

sed 's/use five-minute-interval/use five-minute-interval/g' services.cfg

If you could find the first line number to change, like 250 in this example, then it is not hard:

sed '250,$s/use five-minute-interval/use four-minute-interval/g' services.cfg

Same line works in vi with ':', ex, ed. Usually, you find the first line in vi and say ':.,$s . . . .'

Question here:

 
Does the search string occures only once in any line in your input file or might be occur at multiple times in the same line?
If not , how do you want to proceed

Yes, the search string occurs only once in each line. I'd like to do this from the command line.

if it'll be difficult to make the changes on the "last" 250 occurrence of the search string, then I can work with the first 250 occurrences of the search strings.

thanks.

As suggested by DGPickett , you can use sed.

To get the line number of the 250th occurance:

 
line_num=`awk '/string to search/ {c++; if (c>=250) {c=NR;exit}}END {print c}' input_file`

then you can use $line_num value.

 
sed  "$line_num,$ s/string to search/string to replace/g" input_file

This doesn't seem to be what i want.

ok, the file that needs to be edited is services.cfg.

if i did a grep -c "use five-minute-interval" on that file right now, i would get about 590 lines that have those strings.

but, i want to cut that 590 to half by replacing half of the "five-minute-interval" with "four-minute-interval".

there has to be a way for me to be able to automatically replace the first number of occurrences of a string with another string.

I tried the below but it didn't work. I also tried what you suggested, but it didn't replace the bottom 250 occurrences of the specified strings. :frowning:

sed 's/use five-minute-interval/use four-minute-interval/250' services.cfg

To replace the first 250 numbers of the string you can do something like:

awk 'c<250{c+=sub("use five-minute-interval","use four-minute-interval")}1' file
awk '/use five-minute-interval/ && ++t>=340{sub("use five-minute-interval","use four-minute-interval")}1' infile

try this sed command:

sed '/use five-minute-interval/{x;/^.\{339\}$/{x;s/use five-minute-interval/use four-minute-interval/;b};s/^/./;x;}' yourFile

Hi All, Thanks for all the pointers you have suggested. On the same lines, is it possible to replace the occurrences 20 to 30 of a string in a file, with a new string? Say in file a.cfg, i have 50 occurrence of string "OLD". I wish to replace occurrence 20 to 30 to "NEW". Is this feasible? My thanks in advance. Aravind

Maybe in vi driven by a script to multiply the searches and substitutes, or emacs.