Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sed Capturing Repeating Number Groups

Tags:

bash

unix

macos

sed

I am trying to use sed to capture a group like these examples:

123123 (i would want the first group 123)
144144 (I would want the group 144)

however sed does not seem to realize what \1 is.

Is there any way to do this using sed? I want to replace the first group with a specific string afterwards.

([0-9]+)\1 

I have tried using the above regex yet, sed does not seem to realize what I am trying to do.

also tried this:

~/Desktop$ cat file
123123
23231
12323
123231
12345
144144
~/Desktop$ sed -n 's/.*\b\([[:digit:]]\{1,\}\)\1\b.*/\1/p' file
~/Desktop$ 

~/Desktop$ sed -n -E 's/([0-9]+)\1/specificstring\1/p' file
specificstring12323
specificstring2323
specificstring12323
specificstring14444

~/Desktop$ sed -nE 's/^([0-9]+)\1([^0-9]|$)/\1/p' file
2323
12323
like image 413
A. Hill Avatar asked Nov 02 '25 00:11

A. Hill


1 Answers

Use a BRE, and avoid using + since it is not a part of POSIX REs.

$ cat file
123123
23231
12323
123231
12345
144144
$ 
$ sed -n 's/^\([0-9]\{1,\}\)\1$/\1/p' file
123
144
like image 132
oguz ismail Avatar answered Nov 04 '25 04:11

oguz ismail



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!