Bash - remove all lines beginning with 'P'

前端 未结 5 825
Happy的楠姐
Happy的楠姐 2020-12-09 12:43

I have a text file that\'s about 300KB in size. I want to remove all lines from this file that begin with the letter \"P\". This is what I\'ve been using:

&g         


        
相关标签:
5条回答
  • 2020-12-09 12:55

    Explanation

    1. use ^ to anchor your pattern to the beginning of the line ;
    2. delete lines matching the pattern using sed and the d flag.

    Solution #1

    cat file.txt | sed '/^P/d'
    

    Better solution

    Use sed-only:

    sed '/^P/d' file.txt > new.txt
    
    0 讨论(0)
  • 2020-12-09 12:58

    Use start of line mark and quotes:

     cat file.txt | egrep -v '^P.*'
    

    P* means P zero or more times so together with -v gives you no lines

    ^P.* means start of line, then P, and any char zero or more times

    Quoting is needed to prevent shell expansion.

    This can be shortened to

    egrep -v ^P file.txt
    

    because .* is not needed, therefore quoting is not needed and egrep can read data from file.

    As we don't use extended regular expressions grep will also work fine

    grep -v ^P file.txt
    

    Finally

    grep -v ^P file.txt > new.txt
    
    0 讨论(0)
  • 2020-12-09 13:00

    This works:

    cat file.txt | egrep -v -e '^P'
    

    -e indicates expression.

    0 讨论(0)
  • 2020-12-09 13:17

    Use sed with inplace substitution (for GNU sed, will also for your cygwin)

    sed -i '/^P/d' file.txt
    

    BSD (Mac) sed

    sed -i '' '/^P/d' file.txt
    
    0 讨论(0)
  • 2020-12-09 13:20

    With awk:

    awk '!/^P/' file.txt
    

    Explanation

    1. The condition starts with an ! (negation), that negates the following pattern ;
      • /^P/ means "match all lines starting with a capital P",
    2. So, the pattern is negated to "ignore lines starting with a capital P".
    3. Finally, it leverage awk's behavior when { … } (action block) is missing, that is to print the record validating the condition.

    So, to rephrase, it ignores lines starting with a capital P and print everything else.

    Note

    sed is line oriented and awk column oriented. For your case you should use the first one, see Edouard Lopez's reponse.

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