Show/Compare Line Number Ranges

ShawnCplus 0 Tallied Votes 224 Views Share

I ran across the need to view a specific line of a file so I wrote this up. You can view a line or a range of lines for a file or compare two files. Check the command for the syntax. Drop it in /usr/bin/sln and enjoy.

#!/bin/bash
quiet=0 
if [ $# -le 1 ]
then
  echo "Syntax: sln <start[-end]>  < file >  [ <file> ]"
  echo "Examples: sln 3 some_file.sh"
  echo "          sln 3-5 some_file.sh"
  echo "          sln 3-5 some_file.sh another_file.sh"
  exit
fi

for i in $*
do
  case "$i" in
    "--quiet" | "-q" ) quiet=1;;
  esac
done;

lines=$1
start=${lines%-*}
end=${lines#*-}
count=1
if [ $end -gt $start ]
then
  count=$(($end - $start + 1))
fi

HEADER1="=== Line(s) $start - $end of $2 ==="
HEADER2="=== Line(s) $start - $end of $3 ==="

if [ $quiet -eq 0 ]
then
  echo ""
fi

# Default output
echo $HEADER1
more +$start $2 | head -$count

if [ "$3" != "" ]
then
  if [ $quiet -eq 0 ]
  then
    echo ""
  fi
  echo $HEADER2
  more +$start $3 | head -$count
fi
if [ $quiet -eq 0 ]
then
  echo ""
fi
cfajohnson 7 Shell scripter and author

echo "[1;4;31mSyntax[0m: sln <start[-end]> < file > [ <file> ]"

'for file in $*' will fail if any filenames contain spaces. Use:

for file in "$@"

ShawnCplus 456 Code Monkey Team Colleague

well that notwithstanding this is also completely useless as sed can. already do it :)

sed -n 10,15p file
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.