0

I have a text file with dates in this format: 27/8/2019 I would like to remove all lines except for those that contain 27/8/2019

If I use sed, that would be:

sed -i '/pattern/!d' file.txt

The problem is that when I have a pattern with '/', I have the next error:

sed: -e expression #1, char 5: unknown command: `8'
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
Dau
  • 419
  • 1
  • 5
  • 20
  • 1
    Possible duplicate of [How to replace strings containing slashes with sed?](https://stackoverflow.com/questions/16790793/how-to-replace-strings-containing-slashes-with-sed) – jas Aug 30 '19 at 02:04
  • Note that the *accepted* solution to the "possible duplicate" will not work in this case. Using an alternative delimiter works with replacement, but not matching. Escaping the slashes works with both, but makes a replacement command difficult to read. – Beta Aug 30 '19 at 02:15
  • Note that it's easier to use grep in this case. – Casimir et Hippolyte Aug 30 '19 at 02:16
  • I must eat my last comment; it *is* possible to use an alternative delimiter for pattern matching if you use a backslash in the right place, as @Cyrus points out. – Beta Aug 30 '19 at 04:38

2 Answers2

2

Escape the slashes:

sed -i '/27\/8\/2019/!d' file.txt
Beta
  • 96,650
  • 16
  • 149
  • 150
0

Using awk

awk '/27\/8\/2019/' file.txt

If date is just a sample, use this to keep all date line:

awk '/[0-9]+\/[0-9]+\/[0-9]+/' file.txt

To update file inline with awk

awk '-your code-' file.txt > tmp && mv tmp file.txt
Jotne
  • 40,548
  • 12
  • 51
  • 55