1827769 Members
2744 Online
109969 Solutions
New Discussion

grep command

 
Ridzuan Zakaria
Frequent Advisor

grep command

Hi,

I am trying to grep a word "connect" in files but grep command will return the entire line that contain the word "connect" in.

For example:
file text.txt has the following line:

"Uncomment the next line for more connect information */"

Command:
$ grep connect text.txt

Will return the entire line.

I would like to get just "more connect information" not the entire line or subset of the line but still contain the word "connect".

Is there a way to do this in shell script?

Thanks.
quest for perfections
8 REPLIES 8
Todd McDaniel_1
Honored Contributor

Re: grep command

Grep does return the whole line when a pattern match is made. Im not sure I understand the application of your question.

Are you trying to change the word or import it to another file or script?

Maybe you can offer a bit more explanation...
Unix, the other white meat.
Ridzuan Zakaria
Frequent Advisor

Re: grep command

Hi Todd,

What I am trying to do is that instead of display the entire line from the grep output result, I would like to display subset of the return line.

If "grep connect text.file" will return output:
"your connection to database abc failed"

I would like to display just the "connection to database".

Thanks.
quest for perfections
c_51
Trusted Contributor

Re: grep command

one way is to use awk

awk '
/^connect/ {
if ( NF == 1 ) print $i;
else print $i, $(i+1);
next;
}
/connect$/ {
print $(i-1), $i;
next;
}

/connect/ {
for ( i=1;i<=NF;i++) {
if ( $i ~ "connect" ) {break;}
}
print $(i-1), $i, $(i+1);
}' yourfile

this will print the word before and after "connect".

and i'm sure using perl's patteren matching capabilities would work much better.
c_51
Trusted Contributor

Re: grep command

oops made some cut and paste errors

awk '
/^connect/ {
if ( NF == 1 ) print $1;
else print $1, $2;
next;
}
/connect$/ {
print $(NF-1), $NF;
next;
}

/connect/ {
for ( i=2;iif ( $i ~ "connect" ) {break;}
}
print $(i-1), $i, $(i+1);
}' yourfile
Victor Fridyev
Honored Contributor

Re: grep command

Hi,

I'm not sure, that you can do what you want with grep only. If you know sructure of strings in the file, you can do either:

grep connect text.txt | awk '{print $3,$4,$5}' or
grep connect text.txt |cut -c10-25

HTH
Entities are not to be multiplied beyond necessity - RTFM
Rodney Hills
Honored Contributor

Re: grep command

One line perl-

perl -n -e 'print "$1 $2 $3\n" if /(\*S+)\s+(connect)\s+(\S*)/i' text.txt

HTH

-- Rod Hills
There be dragons...
Gerhard Roets
Esteemed Contributor

Re: grep command

Hi

I am ussuming you just want matches for the word connect and not words that is like reconnect or connection.

grep " connect " file.txt

That should do the trick

Hope this is what you want

Gerhard
Ridzuan Zakaria
Frequent Advisor

Re: grep command

I found the solution. Thanks for the sugestions.
quest for perfections