Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why sed is not honouring the regex replace request

I have a grep result like this

grep file.txt

Nov-06-22 00:01:16 id-03674-09704 
Nov-06-22 00:01:16 id-03642-04246 

and I need to remove from result the id-…..-….. part

I am using this

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

grep file.txt | sed 's/ id-(\d){5}-(\d){5}/ /g'

but it returns this

Nov-06-22 00:01:16 id-03674-09704 
Nov-06-22 00:01:16 id-03642-04246

I checked the regex id-(\d){5}-(\d){5} and it should be ok.
Why sed is not replacing the grep result ?

>Solution :

Since you are using POSIX BRE regex flavor with sed, \d are not recognized as digit matching construct, and {5} are treated as literal {5} strings, not interval quantifiers.

You need to replace \d with [0-9] and use the -E option to enable POSIX ERE syntax (or escape the interval quantifier braces):

sed -E 's/ id-[0-9]{5}-[0-9]{5}//' file
sed 's/ id-[0-9]\{5\}-[0-9]\{5\}//' file

See the online demo:

#!/bin/bash
s='Nov-06-22 00:01:16 id-03674-09704 
Nov-06-22 00:01:16 id-03642-04246'
sed -E 's/ id-[0-9]{5}-[0-9]{5}//' <<< "$s"

Output:

Nov-06-22 00:01:16 
Nov-06-22 00:01:16

Also, consider just removing last column with awk:

awk 'NF{NF-=1};1' file
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading