置換機能を使用してあるファイルの内容を別のファイルにマージする

置換機能を使用してあるファイルの内容を別のファイルにマージする

他のプログラムからデータを取得するシェルスクリプトを作成しています。その変数の値を使用してファイルから読み取った後、いくつかの変更を行った後に別のファイルに追加します。

以下は例です。

readonly file_location=$location
readonly client_id = $id
readonly client_types = $type_of_client

ここで、$location、$id、$type_of_client の値は他のプログラムから渡されます。以下は例です。

$locationは以下のようにフルパス名です。/home/david/data/12345678 $ idは数値です。120 $ type_of_clientはスペースで区切られた単語です。abc def pqr

現在、この場所には、/home/david/data/12345678などのファイルがあります。意味は常に同じなので、ハードコーディングできます。上記のように変数を繰り返してファイル名を生成し、このファイルにヘッダーとフッターを追加して新しいファイルを作成します。そのため、この部分が正しく機能するように、次のコードを使用しました。abc_lop.xmldef_lop.xmlpqr_lop.xml_lop.xmlclient_types

#!/bin/bash

readonly file_location=$location
readonly client_id=$id
readonly client_types=$type_of_client

client_value=`cat "$file_location/client_$client_id.xml"`

for word in $client_types; do
    fn="${word}"_new.xml
    echo "$word"
    echo '<hello_function>' >>"$fn"
    echo '<name>Data</name>' >>"$fn"
    cat "$file_location/${word}_lop.xml" >>"$fn"
    echo '</hello_function>' >>"$fn"
done

2番目にすべきことは、生成されたファイルを特定の場所にclient_$client_id.xmlコピーする必要がある別のXMLファイルがあることです。以下は生成された。以下の関数全体を私が生成したファイルに置き換える必要があります。_new.xmlclient_$client_id.xmlclient_120.xml_new.xml_new.xml

<?xml version="1.0"?>

<!-- some data -->

        <function>
            <name>TesterFunction</name>
            <datavariables>
                <name>temp</name>
                <type>string</type>
            </datavariables>
            <blocking>
                <evaluate>val = 1</evaluate>
            </blocking>
        </function>
    </model>
</ModelMetaData>

したがって、これが私が作成したファイルの場合_new.xml:ファイル全体を上記のファイルにコピーし、ファイル全体TesterFunctionをそのファイルに置き換える必要があります。

<hello_function>
<name>Data</name>
<Hello version="100">

<!-- some stuff here -->

</Hello>
</hello_function>

したがって、最終出力は次のようになります。

<?xml version="1.0"?>

<!-- some data -->

    <hello_function>
    <name>Data</name>
    <Hello version="100">

    <!-- some stuff here -->

    </Hello>
    </hello_function>
    </model>
</ModelMetaData>

ベストアンサー1

これにより、トリックを実行できます。

#!/bin/bash

readonly file_location="$location"
readonly client_id="$id"
readonly client_types="$type_of_client"

## Define the header and footer variables
header='<hello_function>
<name>Data</name>'
footer='</hello_function>'

for word in $client_types
do
    ## Concatenate the header, the contents of the target file and the
    ## footer into the variable $file.
    file=$(printf '%s\n%s\n%s' "$header" "$(cat "$file_location/${word}_lop.xml")" "$footer")

    ## Edit the target file and print
    perl -0pe "s#<function>\s*<name>DUMMYPMML.+?</function>#$file#sm"  model_"$client_id".xml
done

おすすめ記事