Skip to content

Instantly share code, notes, and snippets.

@Chemaclass
Created October 22, 2023 15:06
Show Gist options
  • Save Chemaclass/493aaa5b671d5c0eaedd047652f24e12 to your computer and use it in GitHub Desktop.
Save Chemaclass/493aaa5b671d5c0eaedd047652f24e12 to your computer and use it in GitHub Desktop.
A highlight line function
# highlight_line
#
# arg $1 file path; it can contain the line directly at the end after :
# arg $2 line or range; the line if it was not specified in the file path ($1)
# arg $3 range; the range +- to display from the line
#
# Usage example:
# hl file/path/foo.txt 47
# hl file/path/foo.txt 47 3
# hl file/path/foo.txt:47
# hl file/path/foo.txt:47 3
function hl() {
local file
local line
local range
# Check if argument is provided
if [ -z "$1" ]; then
echo "Error: No argument provided. Usage: highlight_line file_path:line_number [range]"
return 1
fi
# Check if argument contains a colon
if [[ "$1" == *":"* ]]; then
IFS=':' read -r file line <<< "$1"
range="$2"
else
file="$1"
line="$2"
range="$3"
fi
# Check if file exists
if [ ! -f "$file" ]; then
echo "Error: File '$file' does not exist."
return 1
fi
# Check if line number is provided
if [ -z "$line" ]; then
echo "Error: No line number provided. Usage: highlight_line file_path:line_number [range]"
return 1
fi
# Set default range to 5 if not provided
range="${range:-5}"
awk -v line="$line" -v range="$range" '
{
if (NR == line)
print "\033[1;31m" NR, $0 "\033[0m";
else if (NR >= line-range && NR <= line+range)
print NR, $0;
}' "$file"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment