Bash - delete all lines starting with 'P'

I have a text file about 300 KB in size. I want to delete all lines from this file that begin with the letter "P". This is what I used:

> cat file.txt | egrep -v P* 

This does not output to the console. I can use cat in the file without other commands, and it prints in order. My last goal was:

 > cat file.txt | egrep -v P* > new.txt 

The error does not appear, it does not display anything, and if I run the second command, the new .txt is empty. I have to say that I am running Windows 7 with Cygwin installed.

+7
source share
5 answers

Explanation

  • use ^ to bind your pattern to the beginning of the line;
  • remove lines matching pattern with sed and d .

Solution No. 1

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

The best solution

Use sed - only:

 sed '/^P/d' file.txt > new.txt 
+10
source

With awk:

 awk '!/^P/' file.txt 

Explanation

  • The condition begins with ! (denial), which negates the following pattern;
    • /^P/ means "matching all lines starting with capital P ",
  • So, the pattern is reset to " ignore lines starting with capital P ".
  • Finally, it uses awk behavior when there is no { … } (action block), that is, print an entry confirming the condition.

So, to rephrase, he ignores lines starting with capital P and prints everything else .

Note

sed is row oriented and column oriented awk . For your case, you should use the first, see Edward Lopez's answer.

+8
source

Use the beginning of the line and quotation marks:

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

P* means P zero or more times, so no lines are highlighted with -v

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

A quote is required to prevent shell expansion.

It can be shortened to

 egrep -v ^P file.txt 

because .* not required, so quoting is not required, and egrep can read data from a file.

Since we do not use extended regular expressions, grep also works great.

 grep -v ^P file.txt 

Finally

 grep -v ^P file.txt > new.txt 
+2
source

It works:

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

-e stands for expression.

+2
source

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

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

BSD (Mac) sed

 sed -i '' '/^P/d' file.txt 
+1
source

All Articles