$ cat "

Filtering Lines in a Text File using Emacs

"

Quite often when working with large text files, such as log files you want to remove or keep all lines which match a given pattern. If you are working on the command line you would probably use grep to accomplish this. However, if you are editing the file in Emacs you can use the commands flush-lines and keep-lines. Both these commands take a parameter which is the regex to use when matching the lines in the file.

Let's say that you have a text file that looks something like this:

INSERT INTO [User] ...
INSERT INTO [Blog] ...
INSERT INTO [Comment] ...
INSERT INTO [Comment] ...
INSERT INTO [User] ...
INSERT INTO [User] ...

If you are only interested in the lines which insert data into the Comment table you can use keep-lines

M-x keep-lines<enter>
Comment

The buffer would then contain the following text:

INSERT INTO [Comment] ...
INSERT INTO [Comment] ...

If you instead wanted to exclude those same lines you could use flush-lines, in just the same way.

It's worth mentioning that these commands accept full blown regexes as argument, and not just simple strings.

Written by Erik Öjebo 2013-04-03 13:23

    Comments