Re: How to cut the 1st and last 2 lines out of a file



On 2006-06-30, jason.nesbitt@xxxxxxxxx wrote:
I'm looking for an efficient way to cut the 1st and last 2 lines out of
a file. I can get the first line out with "cat <filename> | tail +2l"
but after that I'm lost. Any suggestions?

This script will cut any number of lines from top and bottom of a
file.


# NAME: topntail - remove lines from top and bottom of a file
# USAGE: topntail [-b N] [-e N] [FILE ...]
b=
e=
while getopts b:e: opt
do
case $opt in
b) b=$OPTARG ;;
e) e=$OPTARG ;;
esac
done
shift $(( $OPTIND - 1 ))

case $b$e in
*[!0-9]*) exit 5 ;;
esac

if [ ${e:-1} -eq 0 ]
then
sed "1,${b:-1}d" "$@"
else
awk 'NR > b + e { print buf[ NR % e ] }
{ buf[ NR % e ] = $0 }' b=${b:-1} e=${e:-1} "$@"
fi


--
Chris F.A. Johnson, author <http://cfaj.freeshell.org>
Shell Scripting Recipes: A Problem-Solution Approach (2005, Apress)
===== My code in this post, if any, assumes the POSIX locale
===== and is released under the GNU General Public Licence
.



Relevant Pages

  • Re: chopping off the last few lines.
    ... > various pre-processing actions upon it via a ksh script. ... bottom of a file. ... ## The bufarray is a rotating buffer which contains the last N lines ...
    (comp.unix.shell)
  • Re: Dealing with File Arguments and Spaces
    ... effective solution is the following script. ... I would also like to pass flags to my ... while getopts "$optstring" opt ...
    (comp.unix.shell)
  • Re: Getopts wildcard
    ... For example here's a script called adhoc.sh: ... case ${OPT} in ... echo "$OPT:$OPTARG" ...
    (comp.unix.shell)
  • Re: How to using getopt get value with space ?
    ... > Changed using getopts. ... When input two option the script not work. ... > while getopts hs: opt ...
    (comp.unix.shell)
  • Re: match machine name to user name
    ... :>: query the server from a client for a username based on a machine name. ... :> It reads better if you post inline or at the bottom. ... Is it better to use the script to poll the server or to ...
    (microsoft.public.scripting.vbscript)