If you have a text file and want to search and replace a part of a matched pattern, how would you do it with perl one-liners, sed or python?
For example:
"653433,78"
match with [0-9]{6},[0-9]{2}
.
Change ,
to .
.
Super User is a question and answer site for computer enthusiasts and power users. It only takes a minute to sign up.
Sign up to join this communityYou can use numbered sub groups. i.e:
Find:
([0-9]{6}),([0-9]{2})
Replace:
\1.\2
Example in Python:
import re
inp = '653433,78'
out = re.sub(r'([0-9]{6}),([0-9]{2})', r'\1.\2', inp)
print out
This would give you:
>>>'653433.78'
re.sub(pat, r'\g<1>' + f'{my_number}', str)
You can capture the matched part around the pattern you want to replace and then reuse it in the replace statement.
cat yourfile | perl -p -e "s/([0-9]{6}),([0-9]{2})/\\1.\\2/g"
A more complex solution with lookahead and lookbacks can also be used (but this will not support wildcards such as * and + for your pattern)
cat yourfile | perl -p -e "s/(?<=[0-9]{6}),(?=[0-9]{2})/./g"