특정 문자 ":"가 발견되지 않으면 어떻게 줄을 이전 줄로 이동합니까? [복사]

특정 문자 ":"가 발견되지 않으면 어떻게 줄을 이전 줄로 이동합니까? [복사]

성적표 텍스트 파일이 많이 있습니다. 어느 정도 정리가 되었습니다. 마지막 청소는 다음과 같습니다.

*.txt 파일에 이 내용이 있습니다.

Gary: I said something.
Larry: I said something else.
Mr. John: I said this. And maybe this
and I also said this.
Laura: did i say anything.

나는 이것이 필요하다.

Gary: I said something.
Larry: I said something else.
Mr. John: I said this. And maybe this and I also said this.
Laura: did i say anything.

행을 이동하고 싶습니다.아니요이전 줄에는 콜론(:)이 포함되어 있습니다. 마지막으로, 각 줄에 줄 바꿈으로 끝나는 문자 대화가 포함되기를 원합니다.

나는 이것을 보았다질문하지만 어떻게 해야할지 모르겠습니다. 저는 sed/awk/python/bash/perl 도구라면 무엇이든 사용할 수 있습니다.

답변1

Sed를 사용하면 패턴 공간에 줄을 추가하고 추가된 부분(추가된 개행부터 패턴 끝까지)에 콜론이 아닌 문자만 포함되어 있는지 확인한 다음, 그렇다면 마지막 개행을 공백으로 바꿀 수 있습니다.

sed -e :a -e '$!N; s/\n\([^:]*\)$/ \1/;ta' -e 'P;D' file.txt
Gary: I said something.
Larry: I said something else.
Mr. John: I said this. And maybe this and I also said this.
Laura: did i say anything.

답변2

어때요 awk? 마지막 줄의 복사본을 유지합니다. 콜론이 없으면(NF == 1) 실제 줄을 마지막 줄에 추가하여 두 줄을 동시에 인쇄합니다. $0은 빈 문자열로 설정되므로 기억되지 않습니다.

awk -F: 'NF == 1 {LAST = LAST " " $0; $0 = ""}; LAST {print LAST}; {LAST = $0} END {print LAST}' file
Gary: I said something.
Larry: I said something else.
Mr. John: I said this. And maybe this and I also said this.
Laura: did i say anything.

답변3

또 다른 awk시도:

BEGIN{RS=":";ORS=":"; # use ":", ie. change of speaker, to recognise end of record
      FS="\n"}        # OFS is still " ", so newlines in input converted to spaces in output
!$NF { ORS="" }       # detect last line (no next speaker) and don't append a :
NF>1 {$NF = "\n" $NF} # restore the newline before the speaker's name
{print}               # print the result

답변4

sed -e '
   /:/{$!N;}
   /\n.*:/!s/\n/ /
   P;D
' file.txt

 Gary: I said something.
 Larry: I said something else.
 Mr. John: I said this. And maybe this and I also said this.
 Laura: did i say anything.

관련 정보