Skip to content

Instantly share code, notes, and snippets.

@markburns
Created June 29, 2011 12:40
Show Gist options
  • Save markburns/1053748 to your computer and use it in GitHub Desktop.
Save markburns/1053748 to your computer and use it in GitHub Desktop.
show_line() {
default_context_lines=10
usage() {
echo "show_line <file> <line number> [number of context lines]"
echo "OR:"
echo "show_line <file>:<line number>[:<number of context lines>]"
echo
echo "Usage Examples:"
echo " show_line /etc/profile 15"
echo " show_line /etc/profile 15 10"
echo " show_line /etc/profile:15"
echo " show_line /etc/profile:15:10"
}
check_digits() {
if [[ "$1" = *[!0-9]* ]]
then
echo "Invalid $2: $1. It must be numeric"
return 1
else
return 0
fi
}
file="$1"
if [[ "$file" = *:* ]]
then
line_number="${file#*:}"
file="${file%%:*}"
if [[ "$line_number" == *:* ]]
then
context_lines="${line_number#*:}"
line_number="${line_number%%:*}"
else
context_lines="$default_context_lines"
fi
else
line_number="$2"
context_lines="${3:-$default_context_lines}"
fi
[[ "$file" == "" || "$line_number" == "" || "$context_lines" == "" ]] && usage && return 1
[[ ! -r "$file" ]] && echo "Given file does not exist or is not readable: $file" && return 1
check_digits "$line_number" "line number" || return 1
check_digits "$context_lines" "context lines" || return 1
cat -n "$file" | grep --color -"$context_lines" "^ *$line_number[^0-9]\+.*"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment