tags:

views:

112

answers:

3

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!

+4  A: 
^\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.

iElectric
I think you want that to be `^\s*x\s*=.*$` (to cover *"literal x preceded by an arbitrary count of spaces"*).
Fredrik Mörk
yep, thanks for correction!
iElectric
upvoted just for this line 'what is the input string, what is the output string and your platform/language.'
paan
A: 

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?

please use backticks to format code.
tonfa
A: 

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
MizardX