[lug] Output every xth line?
Tkil
tkil at scrye.com
Fri Nov 21 16:26:10 MST 2003
>>>>> "Matt" == The Matt <thompsma at colorado.edu> writes:
Matt> I need a script that says "starting with line x, output that
Matt> line and every yth line after it". That is, start at line 5 and
Matt> output line 5, 5+y, 5+2y, &c.
If you actually know numeric values:
| perl -lnwe 'BEGIN { $x = shift; $y = shift }
| print if ( ( $. - $x ) % $y ) == 0' x y < in.txt > out.txt
If you want to look for a pattern first:
| perl -lnwe 'BEGIN { $y = shift }
| if ( /pattern/ ) { $x = $. }
| print if $x && ( ( $. - $x ) % $y ) == 0' y < in.txt > out.txt
You can get fancier if the overhead of using the modulo operator is
too high, but for quick and dirty...
A more shellish approach might be to use 'ln(1)' to add line numbers
to each line, then something to strip them out (you could even use a
regex if the numbers work out that way, say odd lines, or every 5 or
10; otherwise, you're probably stuck with awk), then maybe 'cut(1)' to
get rid of the numbers.
I'll stick with perl, I think. :)
t.
Samples:
| $ seq 1 100 > numbers.txt
|
| $ perl -lnwe 'BEGIN { $x = shift; $y = shift }
| > print if ( ( $. - $x ) % $y ) == 0' 5 13 < numbers.txt
| 5
| 18
| 31
| 44
| 57
| 70
| 83
| 96
|
| $ perl -lnwe 'BEGIN { $y = shift }
| > if ( /^5$/ ) { $x = $. }
| > print if $x && ( ( $. - $x ) % $y ) == 0' 13 < numbers.txt
| 5
| 18
| 31
| 44
| 57
| 70
| 83
| 96
More information about the LUG
mailing list