LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Highlight matched pattern upon string (https://www.linuxquestions.org/questions/linux-newbie-8/highlight-matched-pattern-upon-string-4175723522/)

Faki 03-28-2023 06:21 AM

Highlight matched pattern upon string
 
I would like to have a bash function that highlights a matched pattern upon a string.

Code:

cregex ()
 {
  local ptrn="$1"
  local string="$2"
 
  local -r rst="$( tput sgr0 )"
  local -r blu="$( tput bold; tput setaf 39 )"
 
  echo "$string" | sed -E 's/$ptrn/${blu}${ptrn}${rst}/'
 }


But the function in not behaving as I would wish.

For instance

Code:

cregex "tput" "tput bold; tput setaf 39"
does not highlight the word "tput"

pan64 03-28-2023 06:42 AM

grep --color tput <<<'erfa tput f r tput tput adf'

Faki 03-28-2023 06:58 AM

Would this allow a user to specify any pattern and any text, so that the matched text is highlighted? Would the use of "<<<" redirection suffer from code injection vulnerabilities?


All times are GMT -5. The time now is 12:48 PM.