Remove all lines except matching pattern line best practice (sed)
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?
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.
This might work for you:
sed -n '/matchingpattern/p' file.txt
/.../
is an address which may have actions attached in this case p
.
Instead of using sed, which is complicated, use grep.
grep matching_pattern file
This should give you the desired result.
精彩评论