#!/bin/sh set -eu usage() { cat <<-'EOF' Usage: highlight -n LINE_NUMBER -e PATTERN -f FILENAME highlight -h EOF } help() { cat <<-'EOF' Options: -n LINE_NUMBER the specific line number to highligh -e PATTERN the pattern to highlight all over the file -f FILENAME the file to be processed -h, --help show this message Highlight FILENAME: a) with an ANSI background color on LINE_NUMBER; b) with an ANSI foreground color on every occurrence of PATTERN. Useful as a tool for development workflow, when one wants to show a specific matched line, and at the same time visualize all other ocurrences of PATTERN. Examples: Highlight the line 10 of Makefile, and all occurences of "lisp": $ highlight -n10 -e 'lisp' -f Makefile EOF } for flag in "$@"; do case "$flag" in (--) break ;; (--help) usage help exit ;; (*) ;; esac done while getopts 'n:e:f:h' flag; do case "$flag" in (n) LINE_NUMBER="$OPTARG" ;; (e) PATTERN="$OPTARG" ;; (f) FILENAME="$OPTARG" ;; (h) usage help exit ;; (*) usage >&2 exit 2 ;; esac done shift $((OPTIND - 1)) eval "$(assert-arg -- "${LINE_NUMBER:-}" '-n LINE_NUMBER')" eval "$(assert-arg -- "${PATTERN:-}" '-e PATTERN')" eval "$(assert-arg -- "${FILENAME:-}" '-f FILENAME')" graybg="$(printf '\033[7;2;40m')" end="$(printf '\033[0m')" grep -E --color=always -e ^ -e "$PATTERN" "$FILENAME" | perl -pe "s/\x1b\[m/${end}${graybg}/g if $. == $LINE_NUMBER" | sed "${LINE_NUMBER}s|^\(.*\)\$|${graybg}\\1${end}|"