How to get a next line of a matched word?

Hi ,

If I match a word in a file, I want to pick the next line of that matched word.

My file is a below format-

The ntrag trace has auditError
Line5005 contains transaction Ntrag data

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

Here I wanted if I match a word auditError, I need to get the next line
"Line5005 contains transaction Ntrag data"

I don't know what utility you are using, but with awk, you can do something like this:

awk '/auditError/{getline; print}' inputfile

if you have GNU grep, you can use the -A switch

Thanks blowtorch.

awk '/auditError/{getline; print}' inputfile this has helped me a lot.

But how if I wanted to print the next two lines of matched word.

Muktesh,
Try to always specify the entire request at once.
Any change in the original specification could change the entire solution.

In any event, here is a flexible and parametized way to do what you want:

#!/bin/ksh
typeset -i mCntLines=0
mFound="N"
mTotLines=2
mPattern='YourPattern'
while read mLine
do
  mCntGrep=`echo ${mLine} | grep -c "${mPattern}"`
  if [ ${mCntGrep} = "1" ]; then
    mCntLines=0
    mFound="Y"
    continue
  fi
  if [ "$mFound" = "Y" -a ${mCntLines} -lt ${mTotLines} ]; then
    echo ${mLine}
    mCntLines=${mCntLines}+1
  fi
done < input_file

Where:
mPattern --> Your search pattern.
mTotLines --> Number of lines to print after pattern line.

A sed solution:

sed -n '/auditError/ {n;p;}' file

line_no=`cat <file-name> | grep -c <pattern-name>`
req_line=`cat <file-name> | awk '{NE=$line_no-1}'`

PS: Not tested the above one. Pls correct me if I m wrong

Oops.. its NR..not NE

Please ignore my reply.

grep -c returns the no of times, the string appears in file
grep -n returns the line no of the pattern.
awk '{NR=$line_no+1}' returns the line next to the line of pattern

With the above combination, v can get the desired output

Inside the braces, use another 'getline; print' pair. IMO, the simplest way you could do it.

nskworld,
testing a solution on a sample file - might be a good idea! :wink: