리눅스 awk 명령어 사용법 필드 나누기

Linux awk 명령어 사용 방법

awk는 파일의 레코드를 출력하거나 조작하여 데이터화 하는데 목적이 있는 프로그램입니다. 특정 문자열을 추출할 수도 있습니다.

간단하게도 사용이 가능하며 잘만 사용한다면 연산과 무궁무진한 활용도가 있는 명령어입니다.

 

awk는 디자인한 사람들의 약자를 따서 만든 명령어입니다.

Aho + Weinberger + Kernighan.

 

필드

공백값을 기준으로 [$숫자]를 처리한다

 

ls -l을 해보시면 각 필드들이 나오게 됩니다. 필드들은 아래와 같이 분리될 수 있습니다.

-rw-r--r-- 1 root root 0 May 31 14:58 75  

마지막에는 빈칸으로 두었는데, 만약 파일, 디렉토리 이름이 띄어 쓰기가 되어 있다면 띄어쓰기된 문자가 필드에 들어가게 됩니다.

 

띄어쓰기를 만드려면 touch " " 안에 넣어주시면 파일명에 띄어쓰기를 넣을 수 있습니다.

 

awk 레코드 출력

ls -l | awk '{print $3}'

ls -l 에서 3번째 필드를 출력하는 명령어 입니다.

 

ls -l | awk '{print $3 $5}'

3번째와 5번째 필드를 같이 출력하는 명령어입니다.

 

awk '{print $1, $2}' /etc/hosts

/etc/hosts 안에서 1,2번째 필드를 출력하는 명령어입니다. 

 

특정 패턴이 있는 레코드 출력

테스트 파일을 하나 만들어 줬습니다. 여기서 특정 문자가 있는 행을 뽑아낼 수 있습니다.

 

awk '/py/' ./testfile

testfile에서 py로 시작하는 행을 출력하는 명령어입니다.

 

 

 

if문 사용하기

ls -l | awk '{ if ($9 >= 30) print ($0) }'

IF문을 이용해서 9번째 필드가 30이하이면 출력합니다.

 

awk 옵션

Usage: awk [POSIX or GNU style options] -f progfile [--] file ...

Usage: awk [POSIX or GNU style options] [--] 'program' file ...

POSIX options: GNU long options: (standard)

-f progfile --file=progfile

-F fs --field-separator=fs

-v var=val --assign=var=val

Short options: GNU long options: (extensions)

-b --characters-as-bytes

-c --traditional

-C --copyright

-d[file] --dump-variables[=file]

-D[file] --debug[=file]

-e 'program-text' --source='program-text'

-E file --exec=file

-g --gen-pot

-h --help

-i includefile --include=includefile

-l library --load=library

-L[fatal|invalid|no-ext] --lint[=fatal|invalid|no-ext]

-M --bignum

-N --use-lc-numeric

-n --non-decimal-data

-o[file] --pretty-print[=file]

-O --optimize

-p[file] --profile[=file]

-P --posix

-r --re-interval

-s --no-optimize

-S --sandbox

-t --lint-old

-V --version

 

간단하게 알아보았고 심화된 awk 사용 방법은 추후에 하나하나씩 알려드리도록 하겠습니다.

 

 

댓글

Designed by JB FACTORY