1

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?

Ryszard Czech
  • 18,032
  • 4
  • 24
  • 37
gr68
  • 420
  • 1
  • 10
  • 25
  • 1
    See [Why doesn't `\d` work in regular expressions in sed?](https://stackoverflow.com/questions/14671293/why-doesnt-d-work-in-regular-expressions-in-sed) and [Capturing groups and interval quantifiers do not work in sed regex](https://stackoverflow.com/questions/16923147/capturing-groups-and-interval-quantifiers-do-not-work-in-sed-regex) – The fourth bird Nov 08 '22 at 10:29
  • 1
    Your pattern is right, just need to replace `\d` with `[0-9]` – anubhava Nov 08 '22 at 10:40
  • 2
    No, it is not just about lack of `\d` support. Here, OP's problem is also misunderstanding of regex flavors used by `sed`, let alone the quantifier and `grep` usage issues. – Wiktor Stribiżew Nov 08 '22 at 12:48

2 Answers2

3

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
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
3

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
Apex
  • 1,055
  • 4
  • 22
  • 1
    `grep file.txt` would search its standard input for the pattern _file.txt_. The synopsis for _grep_ is: `grep [OPTION...] PATTERNS [FILE...]`. – user1934428 Nov 08 '22 at 10:24