텍스트 파일의 섹션 정렬

텍스트 파일의 섹션 정렬

다음 형식의 많은 섹션이 포함된 파일이 있습니다. 각 섹션 사이에 빈 줄이 있는지 확인하세요. 완성된 파일이 인덱스 이름을 기준으로 알파벳 순서로 각 섹션이 되도록 이 파일을 정렬하고 싶습니다. 이것이 가능합니까?

[monitor:///..]
disabled = true
index = abc
sourcetype= ...

[monitor:///...]
disabled = true
index = def
sourcetype= ...

답변1

사용:

gawk -v RS="" '
  match($0, /index = ([^[:space:]]+)/, m) {
    stanzas[m[1]] = $0
  }
  END {
    PROCINFO["sorted_in"] = "@ind_str_asc"
    ORS = "\n\n"
    for (indx in stanzas) print stanzas[indx]
  }
' file

파일에 다른 섹션을 추가해 보겠습니다.

[monitor:///..]
disabled = true
index = xyz
sourcetype= ...

[monitor:///..]
disabled = true
index = abc
sourcetype= ...

[monitor:///...]
disabled = true
index = def
sourcetype= ...

그런 다음 gawk 명령의 결과는 다음과 같습니다.

[monitor:///..]
disabled = true
index = abc
sourcetype= ...

[monitor:///...]
disabled = true
index = def
sourcetype= ...

[monitor:///..]
disabled = true
index = xyz
sourcetype= ...

(마지막에 빈 줄이 있습니다)

참고자료:

답변2

dirkt의 설명을 사용하여 만든 Bash 함수:

function sort_stanzas() {
    declare file_path="$1"
    cat "$file_path" \
        | sed -z \
            -e 's/\n/\t/g' \
            -e 's/\t\t/\n/g' \
        | sort \
        | sed -z \
            -e 's/\n/\t\t/g' \
            -e 's/\t/\n/g'
}

용법:sort_stanzas <file>

관련 정보