웹사이트 검색

Linux에서 효과적인 파일 작업을 위해 텍스트를 필터링하는 12가지 유용한 명령


이 기사에서는 Linux에서 필터 역할을 하는 여러 명령줄 도구를 검토합니다. 필터는 표준 입력을 읽고 이에 대한 작업을 수행하며 결과를 표준 출력에 쓰는 프로그램입니다.

이러한 이유로 유용한 보고서 생성을 위한 출력 재구성, 파일의 텍스트 수정 및 기타 여러 시스템 관리 작업과 같은 강력한 방법으로 정보를 처리하는 데 사용할 수 있습니다.

다음은 Linux에서 유용한 파일 또는 텍스트 필터 중 일부입니다.

1. Awk 명령

Awk는 뛰어난 패턴 검색 및 처리 언어로, Linux에서 유용한 필터를 구축하는 데 사용할 수 있습니다. Awk 시리즈 1부부터 13부까지 읽으면 사용을 시작할 수 있습니다.

또한 자세한 정보와 사용 옵션을 보려면 awk 매뉴얼 페이지를 읽어보세요.

man awk

2. Sed 명령

sed는 텍스트 필터링 및 변환을 위한 강력한 스트림 편집기입니다. 우리는 이미 sed에 관해 두 가지 유용한 기사를 작성했습니다. 여기에서 해당 내용을 살펴볼 수 있습니다.

  1. GNU 'sed' 명령을 사용하여 Linux에서 파일을 생성, 편집 및 조작하는 방법
  2. 일상적인 Linux 시스템 관리 작업에 유용한 15가지 'sed' 명령 팁과 요령

sed 매뉴얼 페이지에는 제어 옵션과 지침이 추가되었습니다.

man sed

3. Grep, Egrep, Fgrep, Rgrep 명령

이 필터는 주어진 패턴과 일치하는 라인을 출력합니다. 파일이나 표준 입력에서 행을 읽고 기본적으로 일치하는 모든 행을 표준 출력으로 인쇄합니다.

참고: 기본 프로그램은 grep이며, 변형은 아래와 같이 특정 grep 옵션을 사용하는 것과 동일합니다(이들은 여전히 이전 버전과의 호환성을 위해 사용되고 있습니다).

egrep = grep -E
fgrep = grep -F
rgrep = grep -r  

다음은 몇 가지 기본 grep 명령입니다.

tecmint@TecMint ~ $ grep "aaronkilik" /etc/passwd
aaronkilik:x:1001:1001::/home/aaronkilik:

tecmint@TecMint ~ $ cat /etc/passwd | grep "aronkilik"
aaronkilik:x:1001:1001::/home/aaronkilik:

Linux에서 Grep, Egrep 및 Fgrep의 차이점은 무엇입니까?에 대해 자세히 알아볼 수 있습니다.

4. 헤드 명령

head는 파일의 첫 번째 부분을 표시하는 데 사용되며 기본적으로 처음 10줄을 출력합니다. -n num 플래그를 사용하여 표시할 줄 수를 지정할 수 있습니다.

tecmint@TecMint ~ $ head /var/log/auth.log  
Jan  2 10:45:01 TecMint CRON[3383]: pam_unix(cron:session): session opened for user root by (uid=0)
Jan  2 10:45:01 TecMint CRON[3383]: pam_unix(cron:session): session closed for user root
Jan  2 10:51:34 TecMint sudo:  tecmint : TTY=unknown ; PWD=/home/tecmint ; USER=root ; COMMAND=/usr/lib/linuxmint/mintUpdate/checkAPT.py
Jan  2 10:51:34 TecMint sudo: pam_unix(sudo:session): session opened for user root by (uid=0)
Jan  2 10:51:39 TecMint sudo: pam_unix(sudo:session): session closed for user root
Jan  2 10:55:01 TecMint CRON[4099]: pam_unix(cron:session): session opened for user root by (uid=0)
Jan  2 10:55:01 TecMint CRON[4099]: pam_unix(cron:session): session closed for user root
Jan  2 11:05:01 TecMint CRON[4138]: pam_unix(cron:session): session opened for user root by (uid=0)
Jan  2 11:05:01 TecMint CRON[4138]: pam_unix(cron:session): session closed for user root
Jan  2 11:09:01 TecMint CRON[4146]: pam_unix(cron:session): session opened for user root by (uid=0)

tecmint@TecMint ~ $ head  -n 5 /var/log/auth.log  
Jan  2 10:45:01 TecMint CRON[3383]: pam_unix(cron:session): session opened for user root by (uid=0)
Jan  2 10:45:01 TecMint CRON[3383]: pam_unix(cron:session): session closed for user root
Jan  2 10:51:34 TecMint sudo:  tecmint : TTY=unknown ; PWD=/home/tecmint ; USER=root ; COMMAND=/usr/lib/linuxmint/mintUpdate/checkAPT.py
Jan  2 10:51:34 TecMint sudo: pam_unix(sudo:session): session opened for user root by (uid=0)
Jan  2 10:51:39 TecMint sudo: pam_unix(sudo:session): session closed for user root

Linux에서 효과적으로 사용하기 위해 tail 및 cat 명령과 함께 head 명령을 사용하는 방법을 알아봅니다.

5. 꼬리 명령

tail은 파일의 마지막 부분(기본적으로 10줄)을 출력합니다. 표시할 줄 수를 지정하려면 -n num 스위치를 사용하세요.

아래 명령은 지정된 파일의 마지막 5 줄을 출력합니다.

tecmint@TecMint ~ $ tail -n 5 /var/log/auth.log
Jan  6 13:01:27 TecMint sshd[1269]: Server listening on 0.0.0.0 port 22.
Jan  6 13:01:27 TecMint sshd[1269]: Server listening on :: port 22.
Jan  6 13:01:27 TecMint sshd[1269]: Received SIGHUP; restarting.
Jan  6 13:01:27 TecMint sshd[1269]: Server listening on 0.0.0.0 port 22.
Jan  6 13:01:27 TecMint sshd[1269]: Server listening on :: port 22.

또한 tail에는 파일(특히 로그 파일)의 변경 사항을 실시간으로 감시할 수 있는 특수 옵션 -f가 있습니다.

다음 명령을 사용하면 지정된 파일의 변경 사항을 모니터링할 수 있습니다.

tecmint@TecMint ~ $ tail -f /var/log/auth.log
Jan  6 12:58:01 TecMint sshd[1269]: Server listening on :: port 22.
Jan  6 12:58:11 TecMint sshd[1269]: Received SIGHUP; restarting.
Jan  6 12:58:12 TecMint sshd[1269]: Server listening on 0.0.0.0 port 22.
Jan  6 12:58:12 TecMint sshd[1269]: Server listening on :: port 22.
Jan  6 13:01:27 TecMint sshd[1269]: Received SIGHUP; restarting.
Jan  6 13:01:27 TecMint sshd[1269]: Server listening on 0.0.0.0 port 22.
Jan  6 13:01:27 TecMint sshd[1269]: Server listening on :: port 22.
Jan  6 13:01:27 TecMint sshd[1269]: Received SIGHUP; restarting.
Jan  6 13:01:27 TecMint sshd[1269]: Server listening on 0.0.0.0 port 22.
Jan  6 13:01:27 TecMint sshd[1269]: Server listening on :: port 22.

사용 옵션 및 지침의 전체 목록을 보려면 tail 매뉴얼 페이지를 읽어보세요.

man tail

6. 정렬 명령

정렬은 텍스트 파일의 행이나 표준 입력을 정렬하는 데 사용됩니다.

다음은 domains.list라는 파일의 내용입니다.

tecmint@TecMint ~ $ cat domains.list
linux-console.net
linux-console.net
news.linux-console.net
news.linux-console.net
linuxsay.com
linuxsay.com
windowsmint.com
windowsmint.com

간단한 정렬 명령을 실행하여 다음과 같이 파일 내용을 정렬할 수 있습니다.

tecmint@TecMint ~ $ sort domains.list
linuxsay.com
linuxsay.com
news.linux-console.net
news.linux-console.net
linux-console.net
linux-console.net
windowsmint.com
windowsmint.com

sort 명령을 다양한 방법으로 사용할 수 있습니다. 다음과 같이 sort 명령에 대한 유용한 기사를 살펴보세요.

  1. 14 Linux 'sort' 명령의 유용한 예 - 1부
  2. 7가지 흥미로운 Linux 'sort' 명령 예제 - 2부
  3. 수정 날짜 및 시간을 기준으로 파일을 찾고 정렬하는 방법
  4. 마지막 수정 날짜 및 시간을 기준으로 'ls' 명령의 출력을 정렬하는 방법

7. uniq 명령

uniq 명령은 반복되는 줄을 보고하거나 생략하는 데 사용되며 표준 입력에서 줄을 필터링하고 결과를 표준 출력에 씁니다.

입력 스트림에서 sort를 실행한 후 아래 예와 같이 uniq를 사용하여 반복되는 줄을 제거할 수 있습니다.

한 줄의 발생 횟수를 표시하려면 -c 옵션을 사용하고 -i 옵션을 포함하여 비교하는 동안 대소문자 차이를 무시하세요.

tecmint@TecMint ~ $ cat domains.list
linux-console.net
linux-console.net
news.linux-console.net
news.linux-console.net
linuxsay.com
linuxsay.com
windowsmint.com

tecmint@TecMint ~ $ sort domains.list | uniq -c 
2 linuxsay.com
2 news.linux-console.net
2 linux-console.net
1 windowsmint.com 

자세한 사용법 정보 및 플래그는 uniq 매뉴얼 페이지를 읽어보세요.

man uniq

8. fmt 명령

fmt 단순 최적의 텍스트 포맷터로 지정된 파일의 단락 형식을 다시 지정하고 결과를 표준 출력으로 인쇄합니다.

다음은 domain-list.txt 파일에서 추출한 내용입니다.

1.linux-console.net 2.news.linux-console.net 3.linuxsay.com 4.windowsmint.com

위 내용을 표준 목록으로 다시 포맷하려면 최대 선 너비를 정의하는 데 사용되는 -w 스위치와 함께 다음 명령을 실행하십시오.

tecmint@TecMint ~ $ cat domain-list.txt 
1.linux-console.net 2.news.linux-console.net 3.linuxsay.com 4.windowsmint.com

tecmint@TecMint ~ $ fmt -w 1 domain-list.txt
1.linux-console.net 
2.news.linux-console.net 
3.linuxsay.com 
4.windowsmint.com

9. 홍보 명령

pr 명령은 인쇄를 위해 텍스트 파일이나 표준 입력을 변환합니다. 예를 들어 Debian 시스템에서는 다음과 같이 설치된 모든 패키지를 나열할 수 있습니다.

dpkg -l

인쇄할 준비가 된 페이지와 열로 목록을 구성하려면 다음 명령을 실행하십시오.

tecmint@TecMint ~ $ dpkg -l | pr --columns 3 -l 20  

2017-01-06 13:19                                                  Page 1


Desired=Unknown/Install ii  adduser		ii  apg
| Status=Not/Inst/Conf- ii  adwaita-icon-theme	ii  app-install-data
|/ Err?=(none)/Reinst-r ii  adwaita-icon-theme- ii  apparmor
||/ Name		ii  alsa-base		ii  apt
+++-=================== ii  alsa-utils		ii  apt-clone
ii  accountsservice	ii  anacron		ii  apt-transport-https
ii  acl			ii  apache2		ii  apt-utils
ii  acpi-support	ii  apache2-bin		ii  apt-xapian-index
ii  acpid		ii  apache2-data	ii  aptdaemon
ii  add-apt-key		ii  apache2-utils	ii  aptdaemon-data


2017-01-06 13:19                                                  Page 2


ii  aptitude		ii  avahi-daemon	ii  bind9-host
ii  aptitude-common	ii  avahi-utils		ii  binfmt-support
ii  apturl		ii  aview		ii  binutils
ii  apturl-common	ii  banshee		ii  bison
ii  archdetect-deb	ii  baobab		ii  blt
ii  aspell		ii  base-files		ii  blueberry
ii  aspell-en		ii  base-passwd		ii  bluetooth
ii  at-spi2-core	ii  bash		ii  bluez
ii  attr		ii  bash-completion	ii  bluez-cups
ii  avahi-autoipd	ii  bc			ii  bluez-obexd

.....

여기에 사용된 플래그는 다음과 같습니다.

  1. --column은 출력에 생성된 열 수를 정의합니다.
  2. -l은 페이지 길이를 지정합니다(기본값은 66줄).

10. tr 명령

이 도구는 표준 입력에서 문자를 번역하거나 삭제하고 결과를 표준 출력에 씁니다.

tr을 사용하는 구문은 다음과 같습니다.

tr options set1 set2

아래 예를 살펴보면 첫 번째 명령에서 set1( [:upper:] ) 는 입력 문자의 경우(모두 대문자)를 나타냅니다.

그런 다음 set2([:lower:])는 결과 문자가 되는 경우를 나타냅니다. 두 번째 예에서도 마찬가지이며 이스케이프 시퀀스 \n는 새 줄에 출력을 인쇄한다는 의미입니다.

tecmint@TecMint ~ $ echo "WWW.TECMINT.COM" | tr [:upper:] [:lower:]
linux-console.net

tecmint@TecMint ~ $ echo "news.linux-console.net" | tr [:lower:] [:upper:]
NEWS.TECMINT.COM

11. 더 많은 명령

more 명령은 기본적으로 인증서 보기를 위해 만들어진 유용한 파일 열람 필터입니다. 이는 사용자가 [Enter]를 눌러 더 많은 정보를 볼 수 있는 형식과 같은 페이지 형식으로 파일 콘텐츠를 표시합니다.

이를 사용하여 다음과 같은 대용량 파일을 볼 수 있습니다.

tecmint@TecMint ~ $ dmesg | more
[    0.000000] Initializing cgroup subsys cpuset
[    0.000000] Initializing cgroup subsys cpu
[    0.000000] Initializing cgroup subsys cpuacct
[    0.000000] Linux version 4.4.0-21-generic (buildd@lgw01-21) (gcc version 5.3.1 20160413 (Ubuntu 5.3.1-14ubuntu2) ) #37-Ubuntu SMP Mon Apr 18 18:33:37 UTC 2016 (Ubuntu 4.4.0-21.37-generic
 4.4.6)
[    0.000000] Command line: BOOT_IMAGE=/boot/vmlinuz-4.4.0-21-generic root=UUID=bb29dda3-bdaa-4b39-86cf-4a6dc9634a1b ro quiet splash vt.handoff=7
[    0.000000] KERNEL supported cpus:
[    0.000000]   Intel GenuineIntel
[    0.000000]   AMD AuthenticAMD
[    0.000000]   Centaur CentaurHauls
[    0.000000] x86/fpu: xstate_offset[2]:  576, xstate_sizes[2]:  256
[    0.000000] x86/fpu: Supporting XSAVE feature 0x01: 'x87 floating point registers'
[    0.000000] x86/fpu: Supporting XSAVE feature 0x02: 'SSE registers'
[    0.000000] x86/fpu: Supporting XSAVE feature 0x04: 'AVX registers'
[    0.000000] x86/fpu: Enabled xstate features 0x7, context size is 832 bytes, using 'standard' format.
[    0.000000] x86/fpu: Using 'eager' FPU context switches.
[    0.000000] e820: BIOS-provided physical RAM map:
[    0.000000] BIOS-e820: [mem 0x0000000000000000-0x000000000009d3ff] usable
[    0.000000] BIOS-e820: [mem 0x000000000009d400-0x000000000009ffff] reserved
[    0.000000] BIOS-e820: [mem 0x00000000000e0000-0x00000000000fffff] reserved
[    0.000000] BIOS-e820: [mem 0x0000000000100000-0x00000000a56affff] usable
[    0.000000] BIOS-e820: [mem 0x00000000a56b0000-0x00000000a5eaffff] reserved
[    0.000000] BIOS-e820: [mem 0x00000000a5eb0000-0x00000000aaabefff] usable
--More--

12. 덜 명령

less는 위의 more 명령과 반대이지만 추가 기능을 제공하고 대용량 파일의 경우 조금 더 빠릅니다.

more와 같은 방식으로 사용하세요.

tecmint@TecMint ~ $ dmesg | less
[    0.000000] Initializing cgroup subsys cpuset
[    0.000000] Initializing cgroup subsys cpu
[    0.000000] Initializing cgroup subsys cpuacct
[    0.000000] Linux version 4.4.0-21-generic (buildd@lgw01-21) (gcc version 5.3.1 20160413 (Ubuntu 5.3.1-14ubuntu2) ) #37-Ubuntu SMP Mon Apr 18 18:33:37 UTC 2016 (Ubuntu 4.4.0-21.37-generic
 4.4.6)
[    0.000000] Command line: BOOT_IMAGE=/boot/vmlinuz-4.4.0-21-generic root=UUID=bb29dda3-bdaa-4b39-86cf-4a6dc9634a1b ro quiet splash vt.handoff=7
[    0.000000] KERNEL supported cpus:
[    0.000000]   Intel GenuineIntel
[    0.000000]   AMD AuthenticAMD
[    0.000000]   Centaur CentaurHauls
[    0.000000] x86/fpu: xstate_offset[2]:  576, xstate_sizes[2]:  256
[    0.000000] x86/fpu: Supporting XSAVE feature 0x01: 'x87 floating point registers'
[    0.000000] x86/fpu: Supporting XSAVE feature 0x02: 'SSE registers'
[    0.000000] x86/fpu: Supporting XSAVE feature 0x04: 'AVX registers'
[    0.000000] x86/fpu: Enabled xstate features 0x7, context size is 832 bytes, using 'standard' format.
[    0.000000] x86/fpu: Using 'eager' FPU context switches.
[    0.000000] e820: BIOS-provided physical RAM map:
[    0.000000] BIOS-e820: [mem 0x0000000000000000-0x000000000009d3ff] usable
[    0.000000] BIOS-e820: [mem 0x000000000009d400-0x000000000009ffff] reserved
[    0.000000] BIOS-e820: [mem 0x00000000000e0000-0x00000000000fffff] reserved
[    0.000000] BIOS-e820: [mem 0x0000000000100000-0x00000000a56affff] usable
[    0.000000] BIOS-e820: [mem 0x00000000a56b0000-0x00000000a5eaffff] reserved
[    0.000000] BIOS-e820: [mem 0x00000000a5eb0000-0x00000000aaabefff] usable
:

Linux에서 효과적인 파일 탐색을 위한 명령인 'less'가 'more'보다 빠른 이유를 알아보세요.

지금은 여기까지입니다. 여기에 언급되지 않았지만 Linux에서 텍스트 필터 역할을 하는 유용한 명령줄 도구에 대해 아래 설명 섹션을 통해 알려주세요.