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

2 Answers 2

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' 
1
  • For using number variables in replacement strings, named reference syntax can be used: re.sub(pat, r'\g<1>' + f'{my_number}', str) Commented Apr 25, 2019 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" 

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.