줄 끝까지 정규식 다음의 텍스트를 삭제합니다.

줄 끝까지 정규식 다음의 텍스트를 삭제합니다.

이런 파일이 있어요

this is a year (2004); this text is not insteresting
singer elton john; month and year (December, 2005); blah blah
this another year (2007); irrelevant text

새해가 지나면 코드를 자르고 싶습니다.)

this is a year (2004);
singer elton john; month and year (December, 2005);
this another year (2007);

이건 작동하지 않아

sed -E 's/\(.*\)[0-9]{4});\(.*\)/\2/' file

sed나 awk를 사용하여 이 작업을 어떻게 수행할 수 있나요?

답변1

자신이 원하는 것을 적는 효과적인 방법은 다음과 같습니다.

sed -E 's/(.*[0-9]{4}\);).*/\1/' file

yyyy);이렇게 하면 각 줄의 마지막 항목 이후의 모든 줄 문자가 제거됩니다.

당신의 시도는

sed -E 's/\(.*\)[0-9]{4});\(.*\)/\2/' file

그러나 -E확장 정규식 플래그가 활성화되어 있으므로 \( \)일치 그룹은 분리되지 않지만 파일의 리터럴 대괄호는 일치하는 반면 ( )일치 그룹은 분리됩니다. 따라서 괄호가 [0-9]{4})일치하지 않으며 sed가 불평합니다.

sed: -e expression #1, char 28: Unmatched ) or \)

답변2

항상 하나만 있었다면 );간단할 것입니다.

$ sed 's/);.*/);/' file 
this is a year (2004);
singer elton john; month and year (December, 2005);
this another year (2007);

더 많은 것이 있고 마지막 것 이후의 모든 것을 삭제하려는 경우:

$ sed -E 's/(.*)\);.*/\1);/' file 
this is a year (2004);
singer elton john; month and year (December, 2005);
this another year (2007);

)4개의 숫자( ) 뒤에 일치 항목을 입력하려고 했으나 \)[0-9]{4}입력에 해당 숫자가 없기 때문에 작동하지 않습니다 . 나는 당신이 다음과 같은 것을 쓰려고한다고 생각합니다 :

$ sed -E 's/(.*[0-9]{4}\);).*/\1/' file
this is a year (2004);
singer elton john; month and year (December, 2005);
this another year (2007);

답변3

사용 grep(옵션을 지원하는 버전이 있다고 가정 -o)

$ grep -oE '.*[0-9]{4});' file
this is a year (2004);
singer elton john; month and year (December, 2005);
this another year (2007);

-o옵션을 선택하면 grep일치하는 부분만 인쇄됩니다. 따라서 sed이 패턴을 포함하지 않는 줄은 인쇄되지 않으므로 이는 명령과 정확히 동일하지 않습니다 .

답변4

귀하의 예에서는 마지막 줄 이후의 모든 줄을 자릅니다 ;. 이는 sed역참조가 필요하지 않은 간단한 작업입니다 .

$ sed 's/;[^;]*$/;/' file
this is a year (2004);
singer elton john; month and year (December, 2005);
this another year (2007);

또는 다음을 사용하여 awk:

awk -F ';' 'BEGIN { OFS=FS } { $NF=""; print }' file

관련 정보