Ever wanted to get a range of lines extracted from some file? Easy: load into editor, highlight lines, copy (usually Ctrl<c>), go to target, paste (usually Ctrl<v>).
You want to do that from the command line? With UNIX/Linux you have some options, combining the output of wc -l with head and tail.
You could also combine sed and awk (TIMTOWTDI applies):
sed -e '10,15p;4p;s/.*//' file | awk '!/^$/{print $0}' somefile
I'm not aware of Windows tools to do this task.
But anyways, this is unwieldy, specially if you want to read piped input into your editor of choice calling an external command.
Perl to the rescue:
#!/usr/bin/perl -n my $usage; BEGIN { $usage = "usage: $0 linespec file\n" . "linespec example: 2,5,32-42,4\n" . "this extracts lines 2,4,5 and 32 to 42 from file\n"; $spec=shift; die $usage unless $spec; @l=split/,/,$spec; for(@l){ ($s,$e)=split/-/; $e||=$s; $_=[$s,$e]; } } CHECK { unless(@ARGV) { push @ARGV, <DATA>; chomp @ARGV; } die $usage unless @ARGV; $file = $ARGV[0]; } # === loop ==== for $l(@l){ print if $.>=$l->[0] and $.<=$l->[1] } # === end === # END { if ($file) { open $fh,'<', $0; @lines = <$fh>; close $fh; open $fh,'>',$0; for(@lines){ print $fh $_; last if /^__DATA__$/; } print $fh $file,"\n"; } } __DATA__
Above script, concisely named l (or e.g. lines if that one-letter identifier is already taken) and stored somewhere in any of your private $PATH locations, allows you to e.g. in vi
: r ! l 11-13,42,125-234 somefile
and have the specified lines from somefile read into your current buffer after the line of your cursor.
To do the same with emacs, ask LanX, he knows the proper Ctrl-Shift-Meta-Alt-X encantations to do so.
This code is self-modifying: it places the filename it is invoked upon after the __DATA__ token, so if you want to include more lines of the same file, it suffices to say
: r ! l 1234-1500
For that reason this piece of cr.. code is strictly personal and not suitable to be installed system-wide.
|
|---|