csvデータを使用できるbash用の単純なテンプレートエンジンはありますか?

csvデータを使用できるbash用の単純なテンプレートエンジンはありますか?

私はしばしばいくつかのデータをすばやく取得し、bashのテンプレートに適用したいと思います。

たとえば、次のことを想像してみてください。

  $ seq 1 2 | eztemplate 'this is a {1} test'
  this is a 1 test
  this is a 2 test

  $ eztemplate 'this is a {1} test' hi 'there now'
  this is a hi test
  this is a there now test

  $ eztemplate /tmp/template /tmp/alphabet  | head
  this is a a test
  of this system a
  this is a b test
  of this system b
  ...

この目的のために非常に単純なbashスクリプトを作成しましたが、CSVスタイルデータなどのデータ行ごとに複数のパラメータを許可することを検討しています。

次のシナリオでは、私の小さなスクリプトよりも優れたものがすでに存在していますか?

  • デフォルトのUnix posixツールとperlやawkなどの一般的なインストールツールのみが必要です。perlなどの追加のインストールモジュールは必要ありません。
  • データファイル内の各データ行に対して複数のデータ列を許可できます。
  • デフォルトではbashスクリプトなので、他のものをインストールする必要はありません。 :D
  • もう1つの目的は、bashスクリプトに精通していない人に冗長データテンプレートを処理するための簡単なツールを提供することです。

データとテンプレートは非常に多様ですが、私がやりたい最初の例は、JSONペイロードに4つのIDを適用することです。

金型

{
  "tenantId": "{1}",
  "key": "some.key",
  "value": "some.value"
}

データ

my/super/01cbf4e9779649038f0bd753747c8b26
my/test/01cbf4e9779649038f0bd753747c8b26
ez/test/01cbf4e9779649038f0bd753747c8b26
rad/data/df3a47fed39d453f836f9b2196332029

ezテンプレート

#!/usr/bin/env bash
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"; PATH="$DIR:$PATH"

function show_help()
{
  ME=$(basename "$0")
  IT=$(cat <<EOF

  replaces vars in a template, one for each line of stdin

  e.g.

  $ seq 1 2 | $ME 'this is a {1} test'
  this is a 1 test
  this is a 2 test

  $ $ME 'this is a {1} test' hi 'there now'
  this is a hi test
  this is a there now test

  $ $ME /tmp/template /tmp/alphabet
  this is a a test
  of this system a
  this is a b test
  of this system b
  ...

EOF
)
  echo "$IT"
  echo
  exit
}

if [ -z "$1" ]
then
  show_help
fi
if [ "$1" = "help" ] || [ "$1" = '?' ] || [ "$1" = "--help" ] || [ "$1" = "h" ]; then
  show_help
fi

function process_template(){
  DATA=$1
  VAR=$2

  if [ -f "$DATA" ]; then
    DATA=$(cat "$DATA")
  fi

  echo "$DATA" | sed "s#{1}#$VAR#g"
}


TEMPLATE=$1
if [ -t 0 ]
then
  if [ -f "$2" ]; then
    # allow first 2 parameters to be files, TEMPLATE and then DATA
    DATA_FILE=$2
    cat "$DATA_FILE" | while read line
    do
      process_template "$TEMPLATE" "$line"
    done 
  else
    shift;
    for line in "$@" 
    do
      process_template "$TEMPLATE" "$line"
    done
  fi
else
  # loop over lines from stdin
  while IFS= read -r line; do
    process_template "$TEMPLATE" "$line"
  done
fi

ベストアンサー1

あなたが引用した例では、最も自然な解決策は次のとおりです。

$ seq 1 2 | xargs -n1 printf 'this is a %s test\n'

必要に応じて明らかにawk作業と同じです。

おすすめ記事