sed 명령을 사용하여 xml 파일에서 문자 찾기 및 바꾸기가 작동하지 않습니다.

sed 명령을 사용하여 xml 파일에서 문자 찾기 및 바꾸기가 작동하지 않습니다.

myfile.xml이라는 xml 파일이 있습니다.

<!--This is an xml document for test-->
<a><!--This is root node-->
   <b>
     <c>Hi&Welcome</c>
   </b>
   <d>Hello & How are you?</d>
</a>

나는 이런 변신을 원한다

<!--This is an xml document for test-->
<a><!--This is root node-->
   <b>
     <c>Hi&amp;Welcome</c>
   </b>
   <d>Hello &amp; How are you?</d>
</a>

&의 모든 항목을 &로 변경하려면 다음과 같이 sed 명령을 사용하고 있습니다.

sed -i 's:&:&amp;:' myfile.xml

하지만 '정의되지 않은 라벨 'yfile.xml' 오류가 발생합니다. 더 이상 진행할 수 없습니다. 어떻게 해야 하나요?

답변1

당신이 가지고 있지 않다면GNU sed, sed다음에 대한 매개변수가 필요합니다.-i

sed -i.bak 's:&:&amp;:' myfile.xml

백업 파일을 준비하는 것이 좋습니다. 아니면…

… 펄을 사용하세요;)

테스트

perl -pe 's/&/&amp;/' myfile.xml

그리고 만들다내부 편집~와 함께

perl -pi -e 's/&/&amp;/' myfile.xml

하지만 한 번만.

명령 뒤의 내용은 myfile.xml다음과 같습니다.

<!--This is an xml document for test-->
<a><!--This is root node-->
   <b>
     <c>Hi&amp;Welcome</c>
   </b>
   <d>Hello &amp; How are you?</d>
</a>

답변2

특수 문자 때문에 & 탈출해야 합니다. 그리고 그것을 완료하려면 두 번의 패스가 필요합니다.

사용:
1. sed 's|Hi\&|Hi\&amp;|g' yourfile.xml. 그러면 다음이 생성됩니다.

<!--This is an xml document for test-->
<a><!--This is root node-->
   <b>
     <c>Hi&amp;Welcome</c>
   </b>
   <d>Hello & How are you?</d>
</a>
  1. 두 번째 패스는 다음과 같습니다 sed 's|Hello\ \&| \Hello\ \&amp;|g' test.xml. 생산물:

    <!--This is an xml document for test-->
    <a><!--This is root node-->
       <b>
        <c>Hi&amp;Welcome</c>
       </b>
       <d> Hello &amp; How are you?</d>
    </a>
    

    물론 -i스위치를 사용하여 영구적으로 만드십시오.

아래 @terdon 주석을 기반으로 한 또 다른 고급 방법은 다음과 같습니다.

sed -e 's/Hello &/Hello \&amp;/' -e 's/Hi&/Hi\&amp;/' filename.xml

관련 정보