awk를 사용하여 테이블의 행을 재정렬합니다.

awk를 사용하여 테이블의 행을 재정렬합니다.

수백 개의 행이 있는 테이블이 있습니다.

a1 
a2 
a3 
a4 
b1 
b2 
b3 
b4 
c1 
c2 
c3 
c4
... etc.

다음 순서로 상품을 반품하고 싶습니다.

a1
b1
c1
d1
a2
b2
c2
d2
a3
b3
c3

다음 스크립트는 블록의 첫 번째 행을 선택합니다.

$ awk '{if(NR==1||NR%4==1)print}'

하지만 전체 파일에 대해 이 작업을 수행하려면 어떻게 반복해야 합니까?

답변1

이를 이용 sort하여 정렬할 수 있습니다. 특히 알파벳순과 숫자순 정렬을 처리하는 sort일반 정렬을 수행하도록 지시할 수 있습니다 . 보다 일반적인 기호 대신 기호를 사용하여 g문자열에서 어떤 문자를 정렬할지 제어할 수 있습니다 .sortX.YX,Y

예를 들어:

$ sort -k1.2g file
a1
b1
c1
a2
b2
c2
a3
b3
c3
a4
b4
c4

정렬 옵션:

  -k, --key=KEYDEF
          sort via a key; KEYDEF gives location and type
  -g, --general-numeric-sort
         compare according to general numerical value

  KEYDEF is F[.C][OPTS][,F[.C][OPTS]] for start and stop position, where F is
  a field number and C a character  position in the field; both are origin 1,
  and the stop position defaults to the line's end.  If neither -t nor -b is 
  in effect, characters in a field are counted from the beginning of the 
  preceding whitespace.  OPTS is one or  more  single-letter ordering options
  [bdfgiMhnRrV],  which  override  global ordering options for that key.  If 
  no key is given, use the entire line as the key.

답변2

"단계 크기"가 항상 작은 경우(귀하의 경우 4) 빠르고 더러운 접근 방식은 단순히 파일을 여러 번 읽고 각 오프셋에서 레코드를 선택하는 것입니다.

awk 'FNR==1 {k++} !((FNR-k)%4)' file file file file
a1 
b1 
c1 
a2 
b2 
c2 
a3 
b3 
c3 
a4 
b4 
c4

또는 동등하게 GNU Awk(및 해당 BEGINFILE규칙)를 사용하십시오.

gawk 'BEGINFILE{k++} !((FNR-k)%4)' file file file file

관련 정보