Home > Enterprise >  Why sed is not honouring the regex replace request
Why sed is not honouring the regex replace request

Time:11-09

I have a grep result like this

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?

CodePudding user response:

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, or even with cut:

awk 'NF{NF-=1};1' file.txt
cut -d' ' -f1,2 < file.txt

CodePudding user response:

You can simply do it using cut by specifying the delimiter which I suppose is space in your case. You first need to read your file and do the grep then use cut command. Suppose you already have a file with the selected lines then you can use cut as below:

cat file.txt | cut -d' ' -f1,2

output:

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