开发者

Match against word in single quotes

This is a sed and RegEx beginner question, but I was not able to answer it myself through googling.


Szenario

I have got a plain text file like this as the log file of a command:

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开发者_Go百科 'automake' >= 108... ./_autosetup: line 28: type: automake: not found

Desired Outcome

I would like to extract all words within the single quotes, which occur in combination with not found at the end of line.


What I Did and the Problem

Thus, I first grep for not found and pipe the result to sed: (I am using the line of the not found later, thus -n with grep)

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

With this I am getting two errors: First, that it reached end of file while searching ' and second, that the end of file was unexpected.

I also tried

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

to only get the word within the single quotes without the quotes. Only getting the same errors.


Thanks for your help.


Use that line instead:

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

You can use double quotes to quote ' inside the pattern (so you don't have to backquote them.) That expression also includes the quotes. Without the quotes themselves would require using the parentheses inside the quotes:

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

But I guess you already know that.


I know you asked about sed but the fixed-field format of the file makes it suitable for other approaches as well:

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

Note that you don't need to use < since grep can take a file as input.

Using awk:

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

Finally one in bash:

#!/bin/bash

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

outputs:

automake


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜