Remove all lines except matching pattern line best practice (sed)

前端 未结 4 2009
臣服心动
臣服心动 2021-01-03 21:43

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.         


        
相关标签:
4条回答
  • 2021-01-03 22:00
    sed '/pattern/!d' file.txt
    

    But you're reinventing grep here.

    0 讨论(0)
  • 2021-01-03 22:02

    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.

    0 讨论(0)
  • 2021-01-03 22:04

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

    grep matching_pattern file
    

    This should give you the desired result.

    0 讨论(0)
  • 2021-01-03 22:13

    This might work for you:

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

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

    0 讨论(0)
提交回复
热议问题