bash 变量中的着色线

bash 变量中的着色线

我有以下 bash 函数,它使用颜色打印字符串变量中的行。我想使用wl="1,5,8"第 1、5 和 8 行,使其颜色为白色。我怎样才能做到这一点?

kls ()
 {
  local -r wht="$( tput bold; tput setaf 15 )"
  local -r blu="$( tput bold; tput setaf 39 )"

  wl="1,3,5,8"

  if [[ -n "$wl" ]]; then
    printf '%s%s%s\n' "$wht" "$@" "$rst"
  else
    sed -E "s/^ *[{-].*/${blu}&${rst}/" <<< "$@"
  fi
 }

这是一个示例字符串

str="
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8
Line 9"

这是调用kls

kls "$str"

输出应该是

Line 2 
Line 3  White Coloured Text
Line 4
Line 5  White Coloured Text
Line 6
Line 7
Line 8  White Coloured Text
Line 9"

答案1

使用awk并基于第二列(并假设您总是有两列或更多列):

awk -v reset="$rst" -v  white="$wht" -v lines="$wl" '
BEGIN{split(lines,arrLines,",");} 
{ 
   found=0
   for(item in arrLines) {
      if (arrLines[item] == $2) { 
        found=1 ; break 
      }
   }
   if (found) { 
      print white $0 reset 
   } 
   else print $0
}' <<< "$@"

并基于行号:

awk -v reset="$rst" -v  white="$wht" -v lines="$wl" '
BEGIN{split(lines,arrLines,",");} 
{ 
   found=0
   for(item in arrLines) {
      if (arrLines[item] == NR) { 
        found=1 ; break 
      }
   }
   if (found) { 
      print white $0 reset 
   } 
   else print $0
}' <<< "$@"

相关内容