Operating System - HP-UX
1820661 Members
2536 Online
109626 Solutions
New Discussion юеВ

display range of lines from a file

 
SOLVED
Go to solution
Anand_30
Regular Advisor

display range of lines from a file

I have 2 variables m and n that contains some value. I want to use them in the following command:

awk 'NR==$n, NR==$m {print $0}' file.out

to print the lines of file.out whose numbers are stored in the variables m & n.

Can anyone please help me in this. Is there any other ways to display a range of lines from a file. The line numbers should be obtianed from the variables that holds them.

Thanks,
Andy
10 REPLIES 10
curt larson_1
Honored Contributor
Solution

Re: display range of lines from a file

awk 'NR >= '$n'&& NR <= '$m' { print $0;}' file.out
curt larson_1
Honored Contributor

Re: display range of lines from a file

awk -v start=$n -v end=$m '{
if ( NR >= start && NR <= end ) print $0;
}' file.out
curt larson_1
Honored Contributor

Re: display range of lines from a file

awk '
NR > '$n' {exit;}
NR >='$m' {print $0;}' file.out
curt larson_1
Honored Contributor

Re: display range of lines from a file

sed -n "$n,$m p" file.out
curt larson_1
Honored Contributor

Re: display range of lines from a file

ex -s +"$n,$m p|q" file.out

there is a few different ways to do it
Anand_30
Regular Advisor

Re: display range of lines from a file

Thanks all
curt larson_1
Honored Contributor

Re: display range of lines from a file

please assign points for helpful responses
http://66.34.90.71/ITRCForumsEtiquette/
Elmar P. Kolkman
Honored Contributor

Re: display range of lines from a file

Though not the best sulution, this should work too, as long as $m is the larger of the two variables:
head -$m file.out | tail -`expr $m - $n`

The problem with your line is that the shell will not replace $n and $m, because it is enclosed in single quotes, which is needed because of the $0 you use for the print. But you since you want to print the entire line, you can do it also using double qoutes.

Another thing is the way you try to do the range. Do you know beforehand which is the bigger one? If not, a better awk version would be:

awk "BEGIN { if ($n > $m) { start=$m;end=$n} else {start=$n;end=$m}}
NR >= start && NR <= end { print}" file.out
Every problem has at least one solution. Only some solutions are harder to find.
john korterman
Honored Contributor

Re: display range of lines from a file

Hi,
my guess is that you want to grep for a string in a file and have some lines before and after the string displayed. If that is the case, try the attached script, which needs three parameters: $1= the string to grep for, $2= the number of lines to print before and after the string, $3= the file.


regards,
John K.
it would be nice if you always got a second chance
Jakes Louw
Trusted Contributor

Re: display range of lines from a file

How about :
`cat -n file.out | egrep "$n|$m"`
Trying is the first step to failure - Homer Simpson