lecture/기본 개념 및 명령어

grep, sort

infra 2021. 11. 4. 12:03

grep(=Globally find Regular-Expression and Print)

- 특정문자가 몇개인지, 포함된 행을 찾는데 유용하게 사용된다. 실무에서 매우 자주 쓰임.

 

grep [OPTION] 패턴 [FILE]  : 특정 패턴을 검색하는 filtering 개념
정규표현 e$ 문장의 시작이 q로 시작하는 줄
..e$ 문장의 끝이 3글자 중 e로 끝나는 줄
app* 문장의 시작/중간/끝 이 ap와 p의 “0개혹은 그 이상” 의 개수를 갖고 있는 줄
^[at]  문장의 시작 첫 단어가 a 또는 t 로 시작하는 줄 ^: 여집합의 의미
[0-9]  문장의 중간에 숫자 0~9 까지를 포함하고 있는 줄
확장 정규표현 [p]{2} 문장 내 p라는 글자가 연속 두번 나오는 경우
^[a-zA-Z0-9]{3,9 장의 시작이 소문자/대문자/숫자 로 시작하는 3~9길이

 

 

root@ubuntu16:~# ps -x |grep "/bin"
  830 ?        Ssl    0:00 /usr/bin/python3 /usr/share/unattended-upgrades/unattended-upgrade-shutdown --wait-for-signal
 5160 pts/20   S+     0:00 grep --color=auto /bin

 

root@ubuntu16:~# ps -ux |grep "/bin"
root       830  0.0  0.4 175900 19636 ?        Ssl  15:01   0:00 /usr/bin/python3 /usr/share/unattended-upgrades/unattended-upgrade-shutdown --wait-for-signal
root      5162  0.0  0.0  15504   940 pts/20   S+   21:41   0:00 grep --color=auto /bin

 

root@ubuntu16:~# ps -x |grep "/bin" |grep -v "grep"
  830 ?        Ssl    0:00 /usr/bin/python3 /usr/share/unattended-upgrades/unattended-upgrade-shutdown --wait-for-signal

 

process 찾는 명령어 중 /bin 디렉터리는 찾되, grep이라는 단어는 제외하라(-v 옵션)


-i 옵션은 대,소문자를 무시

 옵션없는 grep은 대,소문자를 구분

egrep=grep -E = 패턴을 확장된 정규표현으로 해석함

 

 

root@ubuntu16:~# cat /var/log/syslog |grep "WARN" |wc -l
14
root@ubuntu16:~# cat /var/log/syslog |grep -i "WArn" |wc -l
25
root@ubuntu16:~# cat /var/log/syslog |egrep -i "WArn" |wc -l
25


root@ubuntu16:/boot/grub/locale# grep -v leesh /etc/passwd |wc -l
41
root@ubuntu16:/boot/grub/locale# grep -vc leesh /etc/passwd
41
root@ubuntu16:/boot/grub/locale# cat /etc/passwd |grep -v leesh |wc -l
41

 

 

 

2. sort 명령어

텍스트로 된 파일의 행단위를 정렬할 때 사용하는 명령어. 간단한 txt 문서에서 정렬 작업할 때 주로 사용하며, 특정 DB, 프로그램 및 shell 프로그램 등 입력값으로 사용되는 데이터를 정렬 할 때 편리함.

 

예를 들어 숫자가 엉망진창으로 되어있어도, 다음과 같이 sort명령어는 순서대로 분류할 수 있다.

 

root@ubuntu16:/tmp/sort_test# cat sort_testfile
3       leesh
2       infra
4       hi
5       bye
6       why not?
1       hello

root@ubuntu16:/tmp/sort_test# sort sort_testfile

1       hello
2       infra
3       leesh
4       hi
5       bye
6       why not?

 

기본값으로는 첫번째 column 을 기준으로 분류하는 것을 알 수 있다.

 

sort 예시
  명령어 설명
그림 1 ll | sort

ll | sort -k 9

디렉터리 목록을 분류

디렉터리 목록을 두번째 컬럼으로 기준 분류
(기본값 : 문자열 sorting)
그림 2 ll | sort -k2n
ll | sort -k 2 -n
디렉터리 목록을 두번째 컬럼으로 숫자로 분류
동일한 옵션이고 붙여서 써도 동일
그림 3 ll | sort -5kn
ll | sort -k 5 -n -r
디렉토리 목록을 파일 사이즈별로 소팅 (기본값: 오름차순 -n 옵션)
디렉토리 목록을 파일 사이즈별로 역순 소팅 (내림차순 r옵션)

그림1

 

그림2

 

 

그림3

 

 

'lecture > 기본 개념 및 명령어' 카테고리의 다른 글

awk, sed,  (0) 2021.11.05