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

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

Leave a Reply