1822646 Members
3753 Online
109643 Solutions
New Discussion юеВ

script output

 
SOLVED
Go to solution
Ferdie Castro
Advisor

script output

Hi,

Ive been having this problem doing a script that when it encounters xxx in a particular line it prints n number of line below it. Hope you can help me thanks.

Example cat myfile
xxx
asdfghjkl
aaa
poiuyuiyequye
bbb
opfdpop[o[pop[o
xxx
qwerty
poiu
pdiofgshf

produce output when n=1 (1 line below it)

asdfghjkl
qwerty

produce output when n=2 (print 2 lines below it)

asdfghjkl
aaa
qwerty
poiu
3 REPLIES 3
Graham Cameron_1
Honored Contributor
Solution

Re: script output

You could use awk, and pass in the number of lines to print, as follows.

awk -v lines=1 '
/xxx/ {
for (i=1;i<=lines;i++) {
getline
print
}
} ' myfile
--
Use lines=1, lines=2, or whatever.
/xxx will match "xxx" anywhere on the line, if you only want beginning of line, use /^xxx/
--
Graham
Computers make it easier to do a lot of things, but most of the things they make it easier to do don't need to be done.
Ramkumar Devanathan
Honored Contributor

Re: script output

Ferdie,

#!/usr/bin/ksh
# Filename: script.sh

awk -v string=$1 -v lines=$2 '{
tmplines=lines;
if ($0 ~ string)
{
while (tmplines-- > 0)
{
getline;
print $0;
}
}
}' /tmp/a.txt

# where /tmp/a.txt is your text file with the strings.
# eof

Call this as follows -
# script.sh "xxx" 1
asdfghjkl
qwerty
# script.sh "xxx" 2
asdfghjkl
aaa
qwerty
poiu

HTH.
- ramd.
HPE Software Rocks!
Hein van den Heuvel
Honored Contributor

Re: script output

A much similar problem was recently asked and answered in:

http://forums1.itrc.hp.com/service/forums/questionanswer.do?threadId=237288


My reply there adapted (but untested) for your problem:


awk '//{i=; while (i--) {getline; print $0}}' <


or PERL (assuring a re-start every occurence:

cat | perl -e 'while (<>){print if ($i-->0); $i= if (//)}'