HTML의 문자열을 조회 파일의 값으로 바꿉니다.

HTML의 문자열을 조회 파일의 값으로 바꿉니다.

상황: 다른 파일의 데이터를 사용하여 일부 값을 완성해야 하는 HTML 소스 파일이 있습니다.

강화해야 하는 값은 고유 태그 사이에 있습니다.

<Uniquetag>Mystring1</uniquetag>

파일 2에는 여러 열과 많은 행이 있습니다.

Info1 Mystring1 OtherInfo1 MoreInfo1
Info2 Mystring2 OtherInfo2 MoreInfo2
Info3 Mystring3 OtherInfo3 MoreInfo3
....

그런 다음 내 이벤트를 HTML로 표시하고 싶습니다.

<Uniquetag>Mystring1 - Info1</uniquetag>

file1과 file2는 모두 동적이며 정기적으로 변경됩니다. 각 변경 후에 스크립트를 실행합니다. 파일 1에는 Uniquetag가 포함되어 있지 않을 수 있으므로 아무것도 발견되지 않아야 합니다. MyString1이 file2에서 발견되지 않을 수도 있습니다. 이 경우에는 아무것도 추가하면 안 됩니다.

누구든지 이것에 대해 올바른 방향을 알려줄 수 있습니까?

답변1

"펄"을 사용하세요

다음 메타 코드에 설명된 대로 Perl 스크립트를 사용하여 이를 수행하겠습니다.

for each line in file2:
    read line
    parse line into 4 fields with a pattern match
    build an associative array with $array{field2} = "field2 - field1"

slurp file1 into a single variable f

for each pattern match of /<UniqueTag>(match)</UniqueTag>/ in f:
    replace "match" with $array{match}

답변2

붉은 자갈 벽돌가지다--나가HTML을 안정적으로 구문 분석하려는 시도의 함정.

그러나 HTML이 표시된 대로 형식화되어 있으면 다음과 같이 하면 문제가 해결될 수 있습니다.

expr=
while read -r one two rest
do
  expr="$expr; s/<uniquetag>$two<\/uniquetag>/<uniquetag>$two - $one<\/uniquetag>/"
done < file2
sed "$expr" sourcehtml > targethtml

...결과가 만족스러우면 표현식을 다음 sed과 같이 변경할 수 있습니다.

sed -i "$expr" sourcehtml

...sourcehtml 파일을 그 자리에서 편집하게 하세요.

이 상황을 해결하는 방법에는 여러 가지가 있으며 그 중 일부는 다음과 같습니다.

  • file2의 처음 두 열에는 슬래시 또는 작은따옴표가 있습니다.
  • file2에 줄이 너무 많아 sed 표현식이 너무 커집니다(sed를 여러 번 호출하면 해결됨).
  • 태그는 "uniquetag"와 다르게 대문자로 표시됩니다(답변에서 여는 태그를 소문자로 표기합니다. 틀리면 대문자로 표시합니다).

샘플 실행

처음 세 줄의 "file2"와...

소스 HTML:

<uniquetag>other</uniquetag>
<othertag>other</othertag>
<uniquetag>Mystring1</uniquetag>
<uniquetag>other</uniquetag>
<uniquetag>Mystring2</uniquetag>
<othertag>other</othertag>
<uniquetag>Mystring3</uniquetag>
<uniquetag>other</uniquetag>
<othertag>Mystring3</othertag>

출력은 다음과 같습니다

<uniquetag>other</uniquetag>
<othertag>other</othertag>
<uniquetag>Mystring1 - Info1</uniquetag>
<uniquetag>other</uniquetag>
<uniquetag>Mystring2 - Info2</uniquetag>
<othertag>other</othertag>
<uniquetag>Mystring3 - Info3</uniquetag>
<uniquetag>other</uniquetag>
<othertag>Mystring3</othertag>

관련 정보