바꾸기 기능을 사용하여 한 파일의 내용을 다른 파일로 병합

바꾸기 기능을 사용하여 한 파일의 내용을 다른 파일로 병합

다른 프로그램에서 데이터를 가져오는 쉘 스크립트를 작성 중입니다. 해당 변수 값을 사용하여 파일에서 읽은 후 일부 수정을 한 후 다른 파일에 추가합니다.

아래는 예입니다:

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

이제 두 번째로 해야 할 일은 생성된 파일을 특정 위치 에 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

관련 정보