Seeder
Seeder

Reputation:

Why doesn't this regex work?

The regex:

^ *x *\=.*$   

means "match a literal x preceded by an arbitrary count of spaces, followed by an arbitrary count of spaces, then an equal sign and then anything up to the end of line." Sed was invoked as:

sed -r -e 's|^ *x *\=.*$||g' file

However it doesn't find a single match, although it should. What's wrong with the regex?

To all: thanks for the answers and effort! It seems that the problem was in tabs present in input file, which are NOT matched by the space specifier ' '. However the solution with \s works regardless of present tabs!

Upvotes: 0

Views: 255

Answers (3)

Blitz
Blitz

Reputation: 5671

or maybe '^[ ]*x[ ]*='. It's a bit more compatible, but will not match tabs or the like. And, if you don't need groups, why bother about the rest of the line?

Upvotes: 0

Markus Jarderot
Markus Jarderot

Reputation: 89171

sed processes the file line-by-line, and executes the given program for each. The simplest program that does what you want is

sed -re '/^ *x *=.*$/!d' file
  • "/^ *x *=.*$/" selects each line that matches the pattern.
  • "!" negates the result.
  • "d" deletes the line.

sed will by default print all lines unless told otherwise. This effectively prints lines that matches the pattern.

One alternative way of writing it is:

sed -rne '/^ *x *=.*$/p' file
  • "/^ *x *=.*$/" selects each line that matches the pattern.
  • "p" prints the line.

The difference here is that I used the "-n" switch to suppress the automatic printing of lines, and instead print only the lines I have selected.

You can also use "grep" for this task:

grep -E '^ *x *=.*$' file

Upvotes: 0

iElectric
iElectric

Reputation: 5809

^\s*x\s*=.*$

Maybe you must escape some chars, figure it out one by one.

BTW: Regex tags should really have three requirements:

what is the input string, what is the output string and your platform/language.

Upvotes: 5

Related Questions