5

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 ..

Roney Michael
  • 1,056
  • 1
  • 14
  • 22

2 Answers2

10

You 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'
Roney Michael
  • 1,056
  • 1
  • 14
  • 22
  • For using number variables in replacement strings, named reference syntax can be used: re.sub(pat, r'\g<1>' + f'{my_number}', str) – aksh1618 Apr 25 '19 at 18:38
2

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"