라인 그룹별로 파일 정렬

라인 그룹별로 파일 정렬

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

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)을 사용하여 각 3줄 그룹에서 들여쓰기되지 않은 첫 번째 줄을 기준으로 알파벳순으로 파일을 정렬하는 동시에 기존 그룹 아래에 들여쓰기된 줄을 유지하는 것이 가능합니까?

답변1

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

  • 제비파일( perl -0n)
  • 들여쓰기되지 않은 줄로 입력 분할split(/^(?=\S)/m)
  • 정렬 및 인쇄

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

답변2

<EOL>먼저 sed는 텍스트를 섹션 줄 사이의 구분 기호로 사용하여 각 섹션을 한 줄에 배치합니다 . 그런 다음 섹션을 정렬하고 두 번째 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

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

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는 다음과 같습니다.스테르ing 및 in설명하다주문하다.


또는 any awk(Nul로 구분된 레코드 블록 생성) + sort -z(줄 바꿈 대신 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

관련 정보