7

How do I delete all lines in a text file which do not start with the characters #, & or *? I'm looking for a solution using sed or grep.

Adrian Frühwirth
  • 42,970
  • 10
  • 60
  • 71
user1844845
  • 281
  • 3
  • 7
  • 15

3 Answers3

7

Deleting lines:

With grep

From http://lowfatlinux.com/linux-grep.html :

The grep command selects and prints lines from a file (or a bunch of files) that match a pattern.

I think you can do something like this:

grep -v '^[\#\&\*]' yourFile.txt > output.txt

You can also use sed to do the same thing (check http://lowfatlinux.com/linux-sed.html ):

sed '^[\#\&\*]/d' yourFile.txt > output.txt

It's up to you to decide


Filtering lines:

My mistake, I understood you wanted to delete the lines. But if you want to "delete" all other lines (or filter the lines starting with the specified characters), then grep is the way to go:

grep '^[\#\&\*]' yourFile.txt > output.txt
Barranka
  • 20,547
  • 13
  • 65
  • 83
  • try first with a single expression: `grep -v '^#' yourFile > output`. You may need to escape the characters: `grep -v '^\#' yourFile > output` – Barranka Apr 04 '13 at 22:56
  • But I need to keep lines begins with & or * or # not delete them. I want to delete all other lines. – user1844845 Apr 04 '13 at 23:06
  • @JonathanLeffler Made the correction. Yes, you're right, one command solves it all. Thank you for your feedback – Barranka Apr 05 '13 at 07:13
3
sed -n '/^[#&*].*/p' input.txt > output.txt

this should work.

 sed -ni '/^[#&*].*/p' input.txt

this one will edit the input file directly, be careful +

Sidharth C. Nadhan
  • 2,191
  • 2
  • 17
  • 16
2
egrep '^(&|#|\*)' input.txt > output.txt
Adrian Frühwirth
  • 42,970
  • 10
  • 60
  • 71