37

I am using textmate to edit a file. I would like to remove all the lines not containing a word. Here is an example.

apple ipad
hp touch pad
samsung galaxy tab
motorola xoom

How can i remove all the line not containing the word "pad", and get this result, using Regular Expression??

apple ipad
hp touch pad

Thanks all.

makrom
  • 346
  • 2
  • 12
Victor Lam
  • 3,646
  • 8
  • 31
  • 43
  • 1
    Do you want to *remove* or *keep* all lines with the word "pad"? Does "pad" have to be at the end of the line, or anywhere? – RoToRa Aug 11 '11 at 10:32
  • "pad" is in anywhere. i want to keep the line with "pad", and remove all the other lines. Kizu's answer solved my problem. Thanks for your help RoToRa. :) – Victor Lam Aug 11 '11 at 10:48
  • 1
    Wow. Thanks for that. It just helped a bunch. – Cooper Aug 24 '18 at 00:25

3 Answers3

77

Replace ^(?!.*pad.*).+$ with empty string

kizu
  • 42,604
  • 4
  • 68
  • 95
  • 2
    Would you please explain about this regex? @kizu – natansun Jan 08 '19 at 17:33
  • 5
    @natansun `(?!)` is a “negative lookahead” which is zero-width by itself, but matches only when it won't find the content inside of it. So there we're looking for just anything inside a line — `.+`, then looking if it doesn't contain `pad` prefixed with any other symbols — `(?!.*pad.*)`, and if this expression would be found, we can replace it with an empty string that would basically remove the line. – kizu Jan 09 '19 at 18:18
  • 3
    I tweaked it a little and used `^(?!.*(10039|10038|10037|10036).*).+$\n` to replace lines that don't have any of the words I want and also remove the line break in the process. – Tao Zhang Aug 23 '19 at 19:57
6

I'm not sure about doing this kind of thing using regular expressions but you could easily use grep to do this.

For example, if the file textfile contains this:

apple ipad
hp touch pad
samsung galaxy tab
motorola xoom

Open Terminal, and run this command:

grep pad textfile

It'll output this:

apple ipad
hp touch pad

If you want to save the output to a file you can do something like this:

grep pad textfile > filteredfile
daxnitro
  • 920
  • 6
  • 7
  • Thanks daxnitro. This is a good solution. But kizu's answer is better as I can get the result right inside textmate. But thanks so much for your help. :) – Victor Lam Aug 11 '11 at 10:56
1

This expression will select lines that contain the word pad: ^.*pad.*$

The ^ character indicates the start of a line, the $ character indicates the end, and .* allows for any number of characters surrounding the word.

This may be too wide-ranged for your purpose in its current state - more specific information is needed.

agf
  • 171,228
  • 44
  • 289
  • 238
  • Yup. This can get all the lines with "pad". But I want to remove the lines without this word. I didn't know how to do that before. Thanks for answer. :) – Victor Lam Aug 11 '11 at 10:55
  • Thank you for providing an explanation of characters in the expression. – Fred Jul 01 '16 at 13:37