줄 그룹별로 파일 정렬

줄 그룹별로 파일 정렬

다음과 유사한 내용의 파일이 있는 경우:

FirstSection
    Unique first line in first section
    Unique second line in first section

SecondSection
    Unique first line in second section
    Unique second line in second section

...

NthSection
    Unique first line in Nth section
    Unique second line in Nth section

unix 명령(예: sort, awk)을 사용하여 각 세 줄 그룹에서 들여쓰기되지 않은 첫 번째 줄을 기준으로 파일을 알파벳순으로 정렬하는 동시에 들여쓰기된 줄을 기존 그룹 아래에 유지하는 것이 가능합니까?

답변1

Perl을 사용하면 다음과 같은 내용을 실행할 수 있습니다.

  • 파일을 후루룩 마시다 ( perl -0n)
  • 들여쓰기되지 않은 줄로 입력을 분할합니다.split(/^(?=\S)/m)
  • 정렬 및 인쇄

perl -0ne 'print sort split(/^(?=\S)/m) ' ex 

답변2

먼저 sed는 텍스트를 <EOL>섹션 줄 사이의 구분 기호로 사용하여 각 섹션을 한 줄에 배치합니다. 그런 다음 섹션을 정렬하고 두 번째 sed를 사용하여 각 섹션을 <EOL>개행 문자로 되돌립니다.

sed -r ':r;$!{N;br};s:\n([[:blank:]])(\1*):<EOL>\1\2:g' file|sort|sed -r '/^$/d;:l;G;s:(.*)<EOL>(.*)(\n):\1\3\2:;tl;$s:\n$::'

입력 파일에 문자가 있을 수 있으므로 구분 기호로 문자를 선택하지 않았으므로 <EOL>대신 사용했습니다.

산출:입력 파일의 스타일을 다시 만들기 위해 마지막 섹션을 제외하고 각 섹션 뒤에 줄바꿈을 추가했습니다.

FirstSection
    Unique first line in first section
    Unique second line in first section

NthSection
    Unique first line in Nth section
    Unique second line in Nth section

SecondSection
    Unique first line in second section
    Unique second line in second section

답변3

GNU를 사용하면 각 awk그룹 사이의 줄 바꿈을 기반으로 모든 레코드 그룹을 awk 관련 배열에 보관할 수 있습니다. 그런 다음 배열을 정렬 하고 for 루프 내의 모든 그룹을 인쇄합니다.asort()PROCINFO["sorted_in"]asort()

awk '/^$/{ ++grpNr; next }
{ groups[grpNr]=(groups[grpNr]==""? "" : groups[grpNr] RS) $0 }
END{ asort(groups); 
     for(grp in groups) print groups[grp]
}'  infile

메모PROCINFO["sorted_in"]: 요소를 사용하여 필요한 정렬 유형을 설정할 수 있습니다 . 예를 PROCINFO["sorted_in"]="@val_str_desc"들어우리 배열의 ue는 다음과 같습니다.string 및 in설명주문하다.


또는 any awk(Nul로 구분된 레코드 블록 생성) + sort -z(Newline이 아닌 Nul 문자를 기준으로 정렬) + tr(이전에 추가된 Nul 문자를 로 제거 awk):

<infile awk '/^$/{ ++grpNr; next }
{ groups[grpNr]=(groups[grpNr]==""? "\0" : groups[grpNr] RS) $0 }
END{ for(grp in groups) print groups[grp] }' |sort -z |tr -d '\0'

다음과 같은 입력 파일에 대한 테스트:

BFirstSection
    Unique first line in first section
    Unique second line in first section

DSecondSection
    Unique first line in second section
    Unique second line in second section

Aanothersection...
    ...
    ...

CfourthSection
    Unique first line in Nth section
    Unique second line in Nth section

다음과 같이 출력됩니다.

Aanothersection...
    ...
    ...
BFirstSection
    Unique first line in first section
    Unique second line in first section
CfourthSection
    Unique first line in Nth section
    Unique second line in Nth section
DSecondSection
    Unique first line in second section
    Unique second line in second section

관련 정보