replace every nth occurrence of a pattern using awk
Your code is almost right, i modified it.
To replace every nth occurrence, you need a modular expression.
So for better understanding with brackets, you need an expression like ((i % n) == 0)
awk -v p="@" -v n="5" ' $0~p { i++ } ((i%n)==0) { sub(/^@/, "\n#\n@") }{ print }' in.bib > out.bib
How to use sed or awk or something similar to replace every odd occurrence of character?
With any sed that supports EREs via -E
, e.g. GNU sed and OSX/BSD sed:
$ echo "1,0,2,0,3,0,4,0,5,0,6,0,13,05,24233,55" | sed -E 's/,([^,]+(,|$))/.\1/g'
1.0,2.0,3.0,4.0,5.0,6.0,13.05,24233.55
The above was inspired by @PesaThe's comment to my original answer.
Replace nth occurrence of substring in string
I use simple function, which lists all occurrences, picks the nth one's position and uses it to split original string into two substrings. Then it replaces first occurrence in the second substring and joins substrings back into the new string:
import re
def replacenth(string, sub, wanted, n):
where = [m.start() for m in re.finditer(sub, string)][n-1]
before = string[:where]
after = string[where:]
after = after.replace(sub, wanted, 1)
newString = before + after
print(newString)
For these variables:
string = 'ababababababababab'
sub = 'ab'
wanted = 'CD'
n = 5
outputs:
ababababCDabababab
Notes:
The
where
variable actually is a list of matches' positions, where you pick up the nth one. But list item index starts with0
usually, not with1
. Therefore there is an-1
index andn
variable is the actual nth substring. My example finds 5th string. If you usen
index and want to find 5th position, you'll needn
to be4
. Which you use usually depends on the function, which generates ourn
.
This should be the simplest way, but maybe it isn't the most Pythonic way, because the
where
variable construction needs importingre
library. Maybe somebody will find even more Pythonic way.
Sources and some links in addition:
where
construction: How to find all occurrences of a substring?- string splitting: https://www.daniweb.com/programming/software-development/threads/452362/replace-nth-occurrence-of-any-sub-string-in-a-string
- similar question: Find the nth occurrence of substring in a string
Python - replace every nth occurrence of string
The code you got from the previous question is a nice starting point, and only a minimal adaptation is required to have it change every nth occurence:
def nth_repl_all(s, sub, repl, nth):
find = s.find(sub)
# loop util we find no match
i = 1
while find != -1:
# if i is equal to nth we found nth matches so replace
if i == nth:
s = s[:find]+repl+s[find + len(sub):]
i = 0
# find + len(sub) + 1 means we start after the last match
find = s.find(sub, find + len(sub) + 1)
i += 1
return s
Execute statement every N iterations in Python
How about keeping a counter and resetting it to zero when you reach the wanted number? Adding and checking equality is faster than modulo.
printcounter = 0
# Whatever a while loop is in Python
while (...):
...
if (printcounter == 1000000):
print('Progress report...')
printcounter = 0
...
printcounter += 1
Although it's quite possible that the compiler is doing some sort of optimization like this for you already... but this may give you some peace of mind.
Iterate over every nth element in string in loop - python
If you want to do something every nth step, and something else for other cases, you could use enumerate
to get the index, and use modulus:
sample = "This is a string"
n = 3 # I want to iterate over every third element
for i,x in enumerate(sample):
if i % n == 0:
print("do something with x "+x)
else:
print("do something else with x "+x)
Note that it doesn't start at 1 but 0. Add an offset to i
if you want something else.
To iterate on every nth element only, the best way is to use itertools.islice
to avoid creating a "hard" string just to iterate on it:
import itertools
for s in itertools.islice(sample,None,None,n):
print(s)
result:
T
s
s
r
g
Related Topics
Selecting a Linux I/O Scheduler
How to Append the Output to a File
Userspace VS Kernel Space Driver
How to Access an Environment Variable in a .Desktop File's Exec Line
Permissions Required to Move File to Different Directory in Unix/Linux
Expect - Interrupt Program - Ctrl+C
How to Move a Relative Symbolic Link
How to Install Apxs Module on Apache 2.4.6
Cross Compiling for Mips Router from X86
Calculate and Print the Average Value of Strings in a Column
How to List Running Screen Sessions
Using Awk to Align Columns in Text File
Why Do I Have to Use Bash -L -C Inside My Container