Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to find a line containing certain characters and remove that line

Tags:

regex

I have text file which has lot of character entries one line after another. I want to find all lines which start with :: and delete all those lines.

What is the regular expression to do this?

-AD

like image 841
goldenmean Avatar asked Feb 04 '09 13:02

goldenmean


People also ask

How do I Find a specific character in a regular expression?

There is a method for matching specific characters using regular expressions, by defining them inside square brackets. For example, the pattern [abc] will only match a single a, b, or c letter and nothing else.

How do you break a line in regex?

Line breaks If you want to indicate a line break when you construct your RegEx, use the sequence “\r\n”. Whether or not you will have line breaks in your expression depends on what you are trying to match.

How do I match an entire line in regex?

To expand the regex to match a complete line, add ‹ . * › at both ends. The dot-asterisk sequences match zero or more characters within the current line.


1 Answers

Regular expressions don't "do" anything. They only match text.

What you want is some tools that uses regular expressions to identify a line and then apply some command to those tools.

One such tools is sed (there's also awk and many others). You'd use it like this:

sed -e "/^::/d" < input.txt > output.txt

The part "/^::/" tells sed to apply the following command to all lines that start with "::" and "d" simply means "delete that line".

Or the simplest solution (which my brain didn't produce for some strange reason):

grep -v "^::" input.txt > output.txt
like image 137
Joachim Sauer Avatar answered Oct 26 '22 23:10

Joachim Sauer