简体   繁体   English

为什么这个sed语句不起作用?

[英]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. 另外一个侧面说明我在某些表达式中使用[^,]并且我仍然使用s得到行。 What am I missing? 我错过了什么?

You need to escape + ; 你需要逃避+ ; and fix {[0-9A-Za-z, ]} to {[0-9A-Za-z, ]*} . 并将{[0-9A-Za-z, ]}修复为{[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};

This might work for you (GNU sed): 这可能适合你(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 ; ) 首先使用空格( \\s ),非空格( \\S )和文字( =(){}; )构建一个松散的正则表达式
  • Determine if the above are 1-or-more, zero-or-more or zero-or-one eg 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\\+\\)\\? 确定以上是1还是更多,零或多或零或一,例如一个或多个空格将由\\s\\+ ,零或多个非空格将是\\S*和零或一组分组将是\\(\\s\\+\\S\\+\\)\\?
  • Try and anchor the regexp using ^ for start of string, $ end of string and in a multiline regexp \\n for newline 尝试并使用^作为字符串的开头,字符串的$ end和多行regexp \\n中的新行来锚定正则表达式
  • 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 eg one-to-three ( \\{1,3\\} ) or 3 ( \\{3\\} ) of course a single class, literal or group need not be qualified 进一步细化一个或多个类到特定范围或数字,例如一到三( \\{1,3\\} )或3( \\{3\\} )当然单个类,文字或组不需要合格

HTH HTH

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM