Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference captures in bash regex replacement

Tags:

regex

bash

How can I include the regex match in the replacement expression in BASH?

Non-working example:

#!/bin/bash
name=joshua
echo ${name//[oa]/X\1}

I expect to output jXoshuXa with \1 being replaced by the matched character.

This doesn't actually work though and outputs jX1shuX1 instead.

like image 878
joshuapoehls Avatar asked Apr 11 '11 17:04

joshuapoehls


People also ask

What =~ in bash?

A regular expression matching sign, the =~ operator, is used to identify regular expressions. Perl has a similar operator for regular expression corresponding, which stimulated this operator. Let's have some examples to see the working of =~ operator in Ubuntu 20.04.

How do you check if a string matches a regex in bash?

You can use the test construct, [[ ]] , along with the regular expression match operator, =~ , to check if a string matches a regex pattern (documentation). where commands after && are executed if the test is successful, and commands after || are executed if the test is unsuccessful.

How do I change a pattern in bash?

The 'sed' command is used to replace any string in a file using a bash script. This command can be used in various ways to replace the content of a file in bash. The 'awk' command can also be used to replace the string in a file.

What is Bash_rematch?

$BASH_REMATCH is an array and contains the matched text snippets. ${BASH_REMATCH[0]} contains the complete match. The remaining elements, e.g. ${BASH_REMATCH[1]} , contain the portion which were matched by () subexpressions.


1 Answers

The question bash string substitution: reference matched subexpressions was marked a duplicate of this one, in spite of the requirement that

The code runs in a long loop, it should be a one-liner that does not launch sub-processes.

So the answer is:

If you really cannot afford launching sed in a subprocess, do not use bash ! Use perl instead, its read-update-output loop will be several times faster, and the difference in syntax is small. (Well, you must not forget semicolons.)

I switched to perl, and there was only one gotcha: Unicode support was not available on one of the computers, I had to reinstall packages.

like image 136
18446744073709551615 Avatar answered Oct 03 '22 21:10

18446744073709551615