Linux Commands | File Management | awk Pattern Search and Processing
awk Command
awk is a command for pattern searching and processing. It extracts and processes results from files to produce the desired output.
The name awk comes from the initials of its original developers: Aho, Weinberger, and Kernighan. It is a text-processing programming language created by the GNU Project, available on Unix-like operating systems. It processes text input by line and word, then prints the result.
Syntax
awk 'pattern' filename
awk '{action}' filename
awk 'pattern' '{action}' filename
awk [ -F fs ] [ -v var=value ] [ 'prog' | -f progfile ] [ file ... ]
awk Command Examples
Example 1: Display only the desired field from command output
date
2018년 6월 24일 일요일 17시 16분 54초 KST
date | awk '{print $1}'
2018년
This extracts and displays only the year from the output of the date command.
Example 2: Extract file contents and display only desired fields
cat sample.txt
foo 한글 12
dev 데브 24
kuma 쿠마 33
hello 헬로 55
Extract and display lines containing kuma
awk '/kuma/' sample.txt
kuma 쿠마 33
Display only the second and first fields separated by spaces
awk '{print $2, $1}' sample.txt
한글 foo
데브 dev
쿠마 kuma
헬로 hello
Extract lines containing kuma, then display the second and first fields separated by spaces
awk '/kuma/{print $2, $1}' sample.txt
쿠마 kuma
Example 3: Display fields using a field separator
Split fields by spaces and display the ninth field.
ls -al
total 59384
drwxr-xr-x 28 kimkc staff 952 6 22 22:29 .
drwxr-xr-x+ 80 kimkc staff 2720 6 24 16:57 ..
drwxr-xr-x 21 kimkc staff 714 6 24 16:57 devkuma
drwxr-xr-x 18 kimkc staff 612 1 2 23:12 tutorial
drwxr-xr-x 13 kimkc staff 442 6 16 07:56 workspace
ls -al | awk -F " " '{print $9}'
.
..
devkuma
tutorial
workspace