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.
sed '/pattern/!d' file.txt
But you're reinventing grep
here.
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.
Instead of using sed, which is complicated, use grep.
grep matching_pattern file
This should give you the desired result.
This might work for you:
sed -n '/matchingpattern/p' file.txt
/.../
is an address which may have actions attached in this case p
.