Re: how to extract exact text

Davide Brini <[email protected]>
Newsgroups gmane.editors.sed.user
Message-ID <[email protected]>
On Thu, 19 Sep 2013 13:29:59 +0200, "MOKRANI Rachid"
<[email protected]> wrote:

> Other text [bug 5] hardware
> 
> [bug 256] my software
> 
> My text [bug 1256] 
> 
>  
> 
> How can I extract only the text 
> 
> [bug 5]
> 
> [bug 256]
> 
> [bug 1256]
> 
>  
> 
>  
> 
> The text I need to extract is always [bug XXXXX] 
> 
> XXXX is always different number.

The answer depends on whether there can be multiple occurrences of [bug
XXX] on the same line. If not, it is trivially done with

sed -n 's/.*\(\[bug [0-9]*\)\].*/\1/p' test.txt

If not, the solution is more complex. A solution using \x1 as marker (needs
GNU sed), which also works in the single-occurrence case:

s/\[bug [0-9]*\]/\x1&/g
t ok
d
:ok
s/^[^\x1]*\x1//
s/\(\[bug [0-9]*\]\)[^\x1]*/\1/g
s/\x1/\n/g

In this case it's probably easier to use GNU grep, eg

grep -Eo '\[bug [0-9]+\]' test.txt

or awk or perl, eg

gawk -v RS='\\[bug [0-9]+\\]' 'RT{print RT}' test.txt

perl -ne 'print "$_\n" for (/\[bug \d+\]/g)' test.txt

-- 
D.
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.