23

I want to remove all lines except the line(s) containing matching pattern.

This is how I did it:

sed -n 's/matchingpattern/matchingpattern/p' file.txt

But I'm just curious because I rename matching pattern to the matching pattern itself. Looks like a waste here.

Is there a better way to do this?

Dataman
  • 3,457
  • 3
  • 19
  • 31
kopelkan
  • 1,135
  • 2
  • 9
  • 8

4 Answers4

56
sed '/pattern/!d' file.txt

But you're reinventing grep here.

geekosaur
  • 59,309
  • 11
  • 123
  • 114
  • 14
    Yup. But sed has this nifty --in-place flag that grep does not have. sed -i '/pattern/!d' filename is much easier than grep 'pattern' filename > filename.tmp && mv filename.tmp filename – Geeklab Apr 24 '15 at 08:19
  • Warning: I supplied the --quiet flag to avoid any results to be printed to the terminal, not realizing -i already achieves that in itself. This meant that all lines were deleted, even those matching the pattern. – EriF89 Jul 07 '17 at 10:20
4

grep is certainly better...because it's much faster.

e.g. using grep to extract all genome sequence data for chromosome 6 in a data set I'm working with:

$ time grep chr6 seq_file.in > temp.out

real    0m11.902s
user    0m9.564s
sys 0m1.912s

compared to sed:

$ time sed '/chr6/!d' seq_file.in > temp.out

real    0m21.217s
user    0m18.920s
sys 0m1.860s

I repeated it 3X and ~same values each time.

2

Instead of using sed, which is complicated, use grep.

grep matching_pattern file

This should give you the desired result.

reFORtEM
  • 941
  • 1
  • 9
  • 14
2

This might work for you:

sed -n '/matchingpattern/p' file.txt

/.../ is an address which may have actions attached in this case p.

potong
  • 55,640
  • 6
  • 51
  • 83