Home > OS >  Replace the n-th occurrences of string in files recursively
Replace the n-th occurrences of string in files recursively

Time:10-19

I need to replace the string of n-th occurrences that exists inside files.

The case is like this:

I have 1,000 occurrences of Acme inside files, which I managed to obtain the number through:

find . -type f -exec cat {}   | grep -c 'Acme'

I also had been able to replace all occurrences of Acme through:

grep -rl 'Acme' ./ | LC_ALL=C xargs sed -i '' 's/Acme/NotAcme/g'

However, I face difficulty when I try to only replace the n-th occurrences (E.g. Only replace the first 100 occurrences of Acme.

The furthest I found is to iterate through all the occurrences of Acme through:

grep -roh Acme . | wc -w

Haven't found the way to iterate and replace the n-th occurrences of Acme so far.

Any help will be appreciated. Thanks!

CodePudding user response:

Only replace the first 100 occurrences of Acme:

You may use this find | gnu-awk solution:

find . -type f -exec awk -v RS='Acme' -v repl='NotAcme' -v n=100 '{
   ORS = (NR <= n ? repl : RT)} 1' {} \;

This awk command sets Acme as record separator, enabling awk to split records on each occurrence of string Acme. We keep a max count of replacements 100 in variable n. When current record count NR is less than equal to n then we output repl otherwise we output RT which is same as value matched by RS

CodePudding user response:

$ awk '/Acme/ &&   n <= 4 { sub(/Acme/, "Notacme") } { print }' test 
1 Notacme
2 Notacme
3 Notacme
FOO
4 Notacme
5 Acme
6 Acme
BAR
7 Acme
8 Acme

THis works. Just replace 4 with "N"

  • Related