正規表現パターンに一致する行から印刷をスキップする

正規表現パターンに一致する行から印刷をスキップする

パターンに一致する行から印刷をスキップする方法。printf新しい行が他のパターンと一致するまで、残りの行はその行と一緒に表示されます。

私が望むのは、後続のテキストの色を表すコードWht:ですGrn:Blu:したがって、エクスポートされませんが、色設定を変更するために使用されます。

これは私が今まで持っているものですが、着色を処理しますが、私が望むことをしません。

theone ()
 {
  printf '%s\n' "$@"  \
    | while IFS="" read -r vl; do
       if [[ "$vl" =~ ^[[:space:]]*Wht:[[:space:]]*$ ]]; then
         printf '%s%s%s\n' "${wht}" "$vl" "${rst}"
       elif [[ "$vl" =~ ^[[:space:]]*Grn:[[:space:]]*$ ]]; then
         printf '%s%s%s\n' "${grn}" "$vl" "${rst}"
       elif [[ "$vl" =~ ^[[:space:]]*Blu:[[:space:]]*$ ]]; then
         printf '%s%s%s\n' "${blu}" "$vl" "${rst}"
       else
         printf '%s%s%s\n' "${wht}" "$vl" "${rst}"
       fi
      done
 }

これは例です

var="
Grn:
  Some lines in green
  More green lites
  Green light again

Blu:
  Now turning to blue
  And more blue"

theone "$var"

結果は次のとおりです。

  Some lines in green
  More green lites
  Green light again

  Now turning to blue
  And more blue

ベストアンサー1

問題を解決するPOSIX互換の方法は次のとおりです。

#!/bin/sh

# Colour codes
grn=$(tput setaf 2) blu=$(tput setaf 4) wht=$(tput setaf 7)
rst=$(tput sgr0)

theone()
{
    printf '%s\n' "$@" |
        while IFS= read -r vl
        do
            # Strip leading and trailing space
            ns=${vl##[[:space:]]}
            ns=${ns%%[[:space:]]}

            case "$ns" in
                # Look for a colour token
                Wht:)   use="$wht" ;;
                Grn:)   use="$grn" ;;
                Blu:)   use="$blu" ;;

                # Print a line
                *)      printf "%s%s%s\n" "${use:-$wht}" "$vl" "$rst" ;;
            esac
        done
}

を使用している場合は、bashコンストラクタを使用するのではなく、カラーコードを関連配列に配置してその中にある項目を見つけることもできますcase … esac

#!/bin/bash

theone()
{
    # Colour codes
    declare -A cc=(
        ['Grn:']=$(tput setaf 2)
        ['Blu:']=$(tput setaf 4)
        ['Wht:']=$(tput setaf 7)
    )
    local rst=$(tput sgr0)

    printf '%s\n' "$@" |
        while IFS= read -r vl
        do
            # Strip spaces
            ns=${vl//[[:space:]]/}

            # Look for a defined token
            if [[ -v cc[$ns] ]]
            then
                # Assign the next colour
                use=${cc[$ns]}
            else
                # Print a line
                printf "%s%s%s\n" "${use:-${cc['Wht:']}}" "$vl" "$rst"
            fi
        done
}

おすすめ記事