2011-08-30 117 views
2

这是sed和RegEx初学者问题,但我无法通过Google搜索自己回答。与单引号匹配


SZENARIO

我有这样的一个纯文本文件作为命令的日志文件:

Checking version of 'make' >= 379... succeeded. (382) 
Checking version of 'm4' >= 104... succeeded. (104) 
Checking version of 'pkg-config' >= 15... succeeded. (25) 
Checking version of 'autoreconf' >= 258... succeeded. (268) 
Checking version of 'automake' >= 108... ./_autosetup: line 28: type: automake: not found 

期望的结果

我想要extrac t单引号内的所有单词,与行尾的not found结合使用。


我所做和问题

因此,我第一grepnot found和管道将结果sed:(我使用的not found的线以后,从而-ngrep

grep -n "not found" < textfile.log | sed -n 's/.*\(\'.*\'\).*/\1/p' 

这样我得到两个错误:首先,它在搜索时到达文件结尾第二,文件的结尾是意外的。

我也试过

grep -n "not found" < textfile.log | sed -n 's/.*[\']\(.*\)[\'].*/\1/p' 

只得到单引号内的字不带引号。只有获得相同的错误。


感谢您的帮助。

回答

1

使用该行:

grep -n "not found" < textfile.log | sed -n "s/.*\('.*'\).*/\1/p" 

您可以用双引号引用'模式中(这样你就不必反引号它们。)这种表达也包括引号。没有引号本身就需要在引号内使用圆括号:

grep -n "not found" < textfile.log | sed -n "s/.*'\(.*\)'.*/\1/p" 

但是我想你已经知道了。

+0

感谢。这很容易:) –

+0

不错!然后不要犹豫!只要接受答案! :) –

+0

这适用于将'/'分隔符更改为例如'#'使它更具可读性...... –

1

我知道你问sed但该文件的固定字段格式使其适用于其他方法还有:

$ grep -n "not found" textfile.log | cut -d"'" -f2 
automake 

请注意,您不需要使用<因为grep可以采取文件作为输入。

使用AWK:

$ awk -F"'" '/not found/{print $2}' textfile.log 
automake 

最后一个在bash:

#!/bin/bash 

while read; do 
    if [[ $REPLY == *not\ found* ]] 
    then 
     set -- "$REPLY" 
     IFS="'"; declare -a Array=($*) 
     echo ${Array[1]} 
    fi 
done < textfile.log 

输出:

automake 
+0

我对'grep'使用'<'来抑制文件名的输出。这对我来说毫无用处。感谢使用'awk'的提示。 –

+0

@ T.K。 - grep不输出文件名,只有匹配的行。或者你使用的版本可能不是gnu grep ... –

0
sed -n "/not found$/ {s/^[^']*'\([^']*\).*/\1/; p}" filename