Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove lines from text file not starting with certain characters (sed or grep)

Tags:

text

grep

sed

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.

like image 544
user1844845 Avatar asked Apr 04 '13 22:04

user1844845


2 Answers

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
like image 96
Barranka Avatar answered Sep 30 '22 17:09

Barranka


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 +

like image 33
Sidharth C. Nadhan Avatar answered Sep 30 '22 16:09

Sidharth C. Nadhan