sed 명령은 파일에서 성공적으로 찾아서 바꾸며 새 파일의 모든 내용을 약간 지웁니다.

sed 명령은 파일에서 성공적으로 찾아서 바꾸며 새 파일의 모든 내용을 약간 지웁니다.

test2.txt라는 파일에 이 xml 텍스트가 있습니다.

<This is a line of text with a year=2020 month=12 in it
This line of text does not have a year or month in it
This year=2021 is the current year the current month=1
This is the year=2021 the month=2/>


<This is a line of text with a year=33020 month=12 in it
This line of text does not have a year or month in it
This year=33020 is the current year the current month=1
This is the year=33020 the month=2/>

파일에 대해 이 정규식을 실행합니다. 첫 번째 단락을 전달하고 싶지만 파일의 나머지 부분은 그대로 둡니다.

sed -i -En '/./{H;$!d} ; x ; s/<(This.*2020.*)\/>/<!--\1-->/p' test2.txt

그러나 결과는 sed 명령이 파일의 나머지 문자열을 모두 제거하고 이를 regexp init에 넣은 결과이므로 이제 test2.txt는 다음과 같습니다.

<!--This is a line of text with a year=2020 month=12 in it
This line of text does not have a year or month in it
This year=2021 is the current year the current month=1
This is the year=2021 the month=2-->

정규식을 실행하면서 파일의 다른 텍스트를 유지하려면 어떻게 해야 합니까?

답변1

당신은 sed에게 명시적으로 말합니다.아니요선이 패턴과 일치하지 않는 한 인쇄합니다. 따라서 연산자 뒤의 합계를 제거하면 -n예상대로 작동합니다.ps///

$ sed  -E '/./{H;$!d} ; x ; s/<(This.*2020.*)\/>/<!--\1-->/'  file

<!--This is a line of text with a year=2020 month=12 in it
This line of text does not have a year or month in it
This year=2021 is the current year the current month=1
This is the year=2021 the month=2-->


<This is a line of text with a year=33020 month=12 in it
This line of text does not have a year or month in it
This year=33020 is the current year the current month=1
This is the year=33020 the month=2/>

그러나 이것은 여전히 ​​처음에 추가 줄바꿈을 추가합니다. 다행스럽게도,@필리포스이 문제를 해결하는 방법을 알려주십시오. 다음을 사용하십시오.

$ sed -E '/./{H;1h;$!d} ; x ; s/<(This.*2020.*)\/>/<!--\1-->/'  file
<!--This is a line of text with a year=2020 month=12 in it
This line of text does not have a year or month in it
This year=2021 is the current year the current month=1
This is the year=2021 the month=2-->


<This is a line of text with a year=33020 month=12 in it
This line of text does not have a year or month in it
This year=33020 is the current year the current month=1
This is the year=33020 the month=2/>

또는 원본 파일을 편집합니다.

sed -i.bak -E '/./{H;1h;$!d} ; x ; s/<(This.*2020.*)\/>/<!--\1-->/'  file

답변2

데이터가 일반 XML 문서(일반 XML 노드)를 나타낸다고 가정합니다.할 수 없다속성에 하위 문자열이 포함될 수 있으므로 제안한 방식으로 주석을 처리하세요. --이로 인해 주석이 조기에 종료되고 문서 구조가 손상될 수 있습니다. 노드를 직접 삭제하는 것이 더 안전하며 이는 XML 파서에서는 간단합니다.

문서가 있다고 가정하면

<?xml version="1.0"?>
<root>
  <thing alt="--" year="2019" month="1" day="1"/>
  <thing alt="--" year="2020" month="5" day="13"/>
  <thing year="2021" month="7" day="3"/>
</root>

thing... 속성에 해당 값이 있는 노드를 삭제하려면 다음 을 사용하세요.2020yearxmlstarlet

$ xmlstarlet ed -d '//thing[@year = "2020"]' file.xml
<?xml version="1.0"?>
<root>
  <thing alt="--" year="2019" month="1" day="1"/>
  <thing year="2021" month="7" day="3"/>
</root>

xmlstarlet-L( ) 옵션을 통해 내부 편집을 지원합니다 --inplace.

관련 정보