Search a String and display only word.

Hello Gurus,

Apologies if this Q has been repeated but i was not able to find it :frowning:

I have an input file:
-------------------------------
Replace DB.Employee
as
select
column1
column2
from DB_T.Emp
and DB.Test
and
DB.Dept
and
DB_T.Ter;

------------------------

I want whole word that matches "DB." or "DB_T." i.e my output file should look like:

---------------------------
DB.Employee
DB_T.Emp
DB.Test
DB.Dept
DB_T.Ter
---------------------------
Grep is displaying the whole line but i just want the word.
Thank you in advance.

Hi

# grep -o 'DB.*[^ ;]'  file
DB.Employee
DB_T.Emp
DB.Test
DB.Dept
DB_T.Ter
#

If -o option not available in your grep, try this:

# grep 'DB' file | sed  's/.*\(DB.*[^ ;]\);*/\1/'
DB.Employee
DB_T.Emp
DB.Test
DB.Dept
DB_T.Ter
#

Guru.

Your small set of input implied that there'd be only one DB.* per record. If you have some records which have multiple DB.* words you want to list, then you'll need something like this:

# fomatted for easier reading; comments completely unnecessary....
# cannonicalise each word in <> branch to keep if matched
# if not matched; delete record; loop to next record
# delete all chrs upto first <
# delete all characters between > <  (multiple matches on same record)
# delete leading <
# delete trailing > and any trailing whitespace
# replace remaining > with newline (separate multiple to one per output record)

sed 's/DB[._][^ \t]*/<&>/g; t keep
d 
: keep
{
        s/[^<]*//;
        s/> [^<]*/> /g;
        s/<//g;
        s/>[ \t]*$//;
        s/> */\n/g; 
}' <file

This will print each DB.* word on a separate line. This example assumes whitespace as seperators; you can add any punctuation that should act as a delimiter to the appropriate class specifications. It also will not match something like DBxxNotMe.

Input:
Replace DB.Employee  DBxNOTme
as 
select 
column1
column2
from DB_T.Emp bar DB_T.foo DB.goo
and DB_Testx
DB.Testy      and more text
DB.Testz and    more text and DB.Testa
and 
DB.Depta
and
DB_T.Ter;

Output:                          
DB.Employee
DB_T.Emp
DB_T.foo
DB.goo
DB_Testx
DB.Testy
DB.Testz
DB.Testa
DB.Depta
DB_T.Ter;
tr -s "[ \t]" "\n" <file | grep 'DB[._].*'

Thanks All..!!!