Extract lines from the middle of a file

This script provides that possibility, using sed to actually extract the lines.

10

Votes

#!/usr/bin/bash
# middle.sh
#
#-------------------------------------------------------------------
# Script dat een stuk uit het midden van een file extract
#
# Parameters:
# start = eerste regelnummer
# eind = laatste regelnummer
# num = aantal lijnen
# file = de filename
#-------------------------------------------------------------------

#-------------------------------------------------------------------
# global variables
#-------------------------------------------------------------------

declare -i START
declare -i END
declare -i NUM
FILE=""

#-------------------------------------------------------------------
#defaults
#-------------------------------------------------------------------

function errcho() {
   >&2 echo $@;
}
function print_usage () {
   errcho "Usage: `basename $0` -s start [-e eind|-n num] file"
}


#-------------------------------------------------------------------
# arguments parsing and check
#-------------------------------------------------------------------
while getopts "s:e:n:" o
do
   case "$o" in
   s)    START="$OPTARG";;
   e)    END="$OPTARG";;
   n)    NUM="$OPTARG";;
   [?])  errcho "Invalid options";
         print_usage;
         exit 1;;
   esac
done

shift $(($OPTIND - 1))
FILE=$1

if [ "${START}z" == "z" ]
then
   errcho "<start> is required"
   print_usage
   exit 1
fi

if [ "${FILE}z" == "z" ]
then
   errcho "<file> is required"
   print_usage
   exit 1
fi

#-------------------------------------------------------------------
# lengte bepalen
#-------------------------------------------------------------------

if [ "${END}z" == "z" ]
then
   if [ "${NUM}z" == "z" ]
   then
      errcho "one of <end> and <num> is required"
      print_usage
      exit 1
   else
      let "END = ${START} - 1 + ${NUM}"
   fi
else
   if [ "${NUM}z" == "z" ]
   then
      let "NUM = ${END} - ${START} + 1"
   else
      errcho "<end> and <num> are exclusive"
      print_usage
      exit 1
   fi
fi

#-------------------------------------------------------------------
# check
#-------------------------------------------------------------------

#echo "END = ${END}, NUM = ${NUM}, FILE = ${FILE}"

#-------------------------------------------------------------------
# eigenlijke commando
#-------------------------------------------------------------------

sed -n "${START},${END}p;${END}q" "${FILE}"

exit 0

Vote Here

You must earn at least 1 vote on your snippets to be allowed to vote

Terms Of Use

Privacy Policy

Featured snippets are MIT license

Gears & Masters

Advertise

DevOpsnipp.com © 2020

medium.png