UniqueUsername
UniqueUsername

Reputation: 153

Why doesn't this sed statement work?

I have been working with regular expressions for the past couple days in class. I cannot determine why this expression doesn't work. I am looking for expressions like the following:

value = (struct node){ 5, NULL};
value2 = (structname){ 1, 2 }; 
*pointer = ( bla ){3,4};

Here is the expression I am using:

sed -n '/^[*0-9A-Za-z_]+ *= *( *[0-9A-Za-z_]+ *[0-9A-Za-z_]* *) *{[0-9A-Za-z, ]};/p'     structfile

What am I missing because it returns nothing. Also a side note I have used [^,] in some expressions and I still get lines with , s. What am I missing?

Upvotes: 0

Views: 205

Answers (2)

potong
potong

Reputation: 58371

This might work for you (GNU sed):

sed '/^\S\+\s\+=\s\+(\s*\S\+\(\s\+\S\+\)\?\s*){\s*\S\+\s*,\s*\S\+\s*};/!d' file
  • Start by building a loose regexp using only whitespace (\s), non-whitespace (\S) and literals (=,(,),{,} and ;)
  • Determine if the above are 1-or-more, zero-or-more or zero-or-one e.g. one-or-more whitespace would be represented by \s\+, zero-or-more non-whitespace would be \S* and zero-or-one grouped would be \(\s\+\S\+\)\?
  • Try and anchor the regexp using ^ for start of string, $ end of string and in a multiline regexp \n for newline
  • Build the regexp slowly, left to right, checking each piece as you go along
  • Once you have a working version replace individual whitespace/non-whitespace by more specific character classes
  • Further refine the one-or-more classes to a specific range or number e.g. one-to-three (\{1,3\}) or 3 (\{3\}) of course a single class, literal or group need not be qualified

HTH

Upvotes: 1

Marcus
Marcus

Reputation: 6839

You need to escape +; and fix {[0-9A-Za-z, ]} to {[0-9A-Za-z, ]*}.

sed -n '/^[*0-9A-Za-z_]\+ *= *( *[0-9A-Za-z_]\+ *[0-9A-Za-z_]* *) *{[0-9A-Za-z, ]*};/p' structfile


me@localhost:~$ cat structfile 
value = (struct node){ 5, NULL};
value2 = (structname){ 1, 2 }; 
*pointer = ( bla ){3,4};
not astruct
notastructstr =

me@localhost:~$ sed -n '/^[*0-9A-Za-z_]\+ *= *( *[0-9A-Za-z_]\+ *[0-9A-Za-z_]* *) *{[0-9A-Za-z, ]*};/p' structfile
value = (struct node){ 5, NULL};
value2 = (structname){ 1, 2 }; 
*pointer = ( bla ){3,4};

Upvotes: 1

Related Questions