-
-
Save Firehed/4325417 to your computer and use it in GitHub Desktop.
lif: get the specified line of a file, optionally surrounded by lines of context copy to a directory in your $PATH (I'd suggest ~/bin), chmod +x, and have fun `lif -h` for help
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| context=0 | |
| usage() { | |
| cat <<EOF | |
| lif: Line in File | |
| Usage: | |
| lif [-c context] line [file] | |
| or | |
| lif [-c context] [file] line | |
| or | |
| echo "some unix pipe" | lif [-c context] line | |
| lif will print the line in file (or stdin) at the specified line number, surrounded by the specified amount of context | |
| EOF | |
| exit 0 | |
| } | |
| while getopts "hc:" OPTION | |
| do | |
| case $OPTION in | |
| c) | |
| context=$OPTARG | |
| ;; | |
| h) | |
| usage | |
| ;; | |
| esac | |
| done | |
| #normalize the input | |
| shift $(($OPTIND - 1)) | |
| if [ -t 0 ] | |
| then | |
| # terminal | |
| if [ $# -lt 2 ] | |
| then | |
| usage | |
| fi | |
| if [ -a $1 ] | |
| then | |
| file=$1 | |
| line=$2 | |
| else | |
| file=$2 | |
| line=$1 | |
| fi | |
| headLen=$(($line+$context)) | |
| tailLen=$((2*$context+1)) | |
| head -$headLen $file | tail -$tailLen | |
| else | |
| # pipe | |
| if [ $# -ne 1 ] | |
| then | |
| usage | |
| fi | |
| lineNum=1 | |
| startLine=$(($1-$context)) | |
| endLine=$(($1+$context)) | |
| while read line | |
| do | |
| if [ $lineNum -ge $startLine ] | |
| then | |
| echo $line | |
| fi | |
| if [ $lineNum -ge $endLine ] | |
| then | |
| break; | |
| fi | |
| lineNum=$(($lineNum+1)) | |
| done | |
| fi | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment