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

2番目の列を使用awkしてベースにします(常に2つ以上の列があるとします)。

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
}' <<< "$@"

おすすめ記事