LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (https://www.linuxquestions.org/questions/linux-general-1/)
-   -   shell script to find an word or words from a line (https://www.linuxquestions.org/questions/linux-general-1/shell-script-to-find-an-word-or-words-from-a-line-641765/)

rakesh.tandur 05-12-2008 08:28 PM

shell script to find an word or words from a line
 
Hi,

What is the command to find the word or words from a given line.

I will be opening a file and reading line by line. Need to check for an certain word or words from that line, if its present then have to append the next 3 line ( including the present line into a file).

This i need to implement using shell script.

Please let me know ur suggestions on it.
Thanks in advance.

Regards
-Rakesh

gilead 05-12-2008 08:46 PM

Tools like grep and sed can find patterns on lines within files. To append lines, I'd recommend sed. There's a tutorial here that should help with what you want to do.

I'm not at a box where I can write/test an example for you at the moment.

davimint 05-12-2008 11:08 PM

Setup a test file and see if this is what your wanting. This should print the following three lines of the pattern and the pattern line. If the pattern is in one of the extra lines it prints it will not match that as a pattern. So this really may not help if it's what you want then all you have to do is decide how to use it in the scrip.

Code:

sed -ne '/pattern/{N;N;N;p}' file

chrism01 05-12-2008 11:52 PM

> grep -A3 qwe t.t
qwe
asd
zxc
iop

> cat t.t
12345
qwe
asd
zxc
iop


man grep

rakesh.tandur 05-13-2008 11:41 AM

That doesnt solve my problem.

Example:
file ex.txt has the following lines:
----------------------------
abc hfgsdf kjf sd kj
gfh kjf df efh rakesh fh
jsdhf sjhf sjhdf hf
hsd hsd ljhsd ds s
hsf f vs fsdg
---------------------------
using the shell script i will be opening the file and reading line by line. what my requirement is when ever i read a line, i need to check for the word rakesh, if its present then i need to get the 3 line including the line which has rakesh..

so i need below 3 lines when i check for word rakesh in a line
-----------------------
gfh kjf df efh rakesh fh
jsdhf sjhf sjhdf hf
hsd hsd ljhsd ds s
----------------------

Note this file will have more then one line with the word rakesh.

Please let me know how to get it.

Regards
-Rakesh

pixellany 05-13-2008 01:57 PM

Look at the -A option to GREP. You can specify the number of lines after the match. ("man grep" for all the details)

Also, someone already posted how to do it with SED. Did you try that?

After either grep or sed, you'll need the redirection operator to write to a new file...eg:
grep -AX <pattern> filename > newfilename


All times are GMT -5. The time now is 10:13 AM.