![특정 문자 ":"가 발견되지 않으면 어떻게 줄을 이전 줄로 이동합니까? [복사]](https://linux55.com/image/140517/%ED%8A%B9%EC%A0%95%20%EB%AC%B8%EC%9E%90%20%22%3A%22%EA%B0%80%20%EB%B0%9C%EA%B2%AC%EB%90%98%EC%A7%80%20%EC%95%8A%EC%9C%BC%EB%A9%B4%20%EC%96%B4%EB%96%BB%EA%B2%8C%20%EC%A4%84%EC%9D%84%20%EC%9D%B4%EC%A0%84%20%EC%A4%84%EB%A1%9C%20%EC%9D%B4%EB%8F%99%ED%95%A9%EB%8B%88%EA%B9%8C%3F%20%5B%EB%B3%B5%EC%82%AC%5D.png)
성적표 텍스트 파일이 많이 있습니다. 어느 정도 정리가 되었습니다. 마지막 청소는 다음과 같습니다.
*.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.