Hack 17. Grep ã³ãã³ã
grep ã³ãã³ãã¯ãã¡ã¤ã«ããæå®ããããã¹ããæ¤ç´¢ããããã«ä½¿ç¨ããã¾ãã
ããã¯ä¿¡ããããªãã»ã©å¼·åãªã³ãã³ãã§ããããã®ãªãã·ã§ã³ãããã¾ãã
Syntax: grep [options] pattern [files]
ãã¡ã¤ã«ä¸ã®æå®ãããã¼ã¯ã¼ãã«ããããããã¹ã¦è¡ãã¿ã¤ããã«ã¯ã©ã®ããã«ã§ããã§ããããï¼
ãã®ä¾ã§ã¯ãgrep 㯠/etc/passwd ãã¡ã¤ã«ã®ä¸ã®ããã¹ã John ãæ¤ç´¢ãã¾ãã
ãããããè¡ããã¹ã¦è¡¨ç¤ºãã¾ãã
# grep John /etc/passwd jsmith:x:1082:1082:John Smith:/home/jsmith:/bin/bash jdoe:x:1083:1083:John Doe:/home/jdoe:/bin/bash
ãªãã·ã§ã³ -v ã¯ããããããã®ä»¥å¤ã®è¡ããã¹ã¦è¡¨ç¤ºãã¾ãã
以ä¸ã®ä¾ã§ã¯ã/etc/passwd ãã John ã«ã¯ãããããªãè¨é²ãã¹ã¦ã表示ãã¾ãã
注æ: /etc/password ã«ã¯ããã¤ãè¡ãããã¾ãããJohn ã¨ããåèªãå«ãã§ãã¾ããã
åºåã®æåã®è¡ã¯ä»¥ä¸ã®ããã«ãªãã¾ãã
# grep -v John /etc/passwd jbourne:x:1084:1084:Jason Bourne:/home/jbourne:/bin/bash
æå®ãããã¡ã¤ã«ã§ããã¹ããã¿ã¼ã³ãããããã®ã¯ä½è¡ã§ããããï¼
以ä¸ã®ä¾ã§ã¯ã/etc/password ãã¡ã¤ã«å
ã« john ã¨ããããã¹ã ãå«ããã¼ã¿ã«ã®è¡æ°ã表示ãã¾ãã
# grep -c John /etc/passwd 2
ãªãã·ã§ã³ -cv ãæå®ãããã¨ã§ãæå®ãããã¿ã¼ã³ã«ãããããªããã¼ã¿ã«è¡æ°ãåå¾ã§ãã¾ãã
# grep -cv John /etc/passwd 39
大æåå°æåãç¡è¦ããããã¹ãã®æ¤ç´¢ãã©ã®ããã«ããã§ããããï¼
ãªãã·ã§ã³ -i (ã±ã¼ã¹ãç¡è¦)ã渡ãã¾ãã
æ¤ç´¢ä¸ã¯å¤§æåå°æåãç¡è¦ããã¾ãã
# grep -i john /etc/passwd jsmith:x:1082:1082:John Smith:/home/jsmith:/bin/bash jdoe:x:1083:1083:John Doe:/home/jdoe:/bin/bash
æå®ãããã¿ã¼ã³ã«ãããããããã¹ãããã¹ã¦ã®ãµããã£ã¬ã¯ããªããæ¤ç´¢ããã«ã¯ï¼
ãªãã·ã§ã³ -r (å帰) ã使ç¨ãã¾ãã
以ä¸ã®ä¾ã§ã¯ã/home/users ä¸ã®ãã¹ã¦ã®ãã£ã¬ã¯ããªãã大æåå°æåãç¡è¦ãã¦
ããã¹ã "john" ãæ¤ç´¢ãã¾ãã
"ãã¡ã¤ã«å: ãã¿ã¼ã³ã«ãããããè¡" ã¨ããå½¢å¼ã§åºåããã¾ãã
ãªãã·ã§ã³ -l ã渡ããã¨ãã§ãã¾ãã
ããã¯ãã¿ã¼ã³ã«ããããããã¡ã¤ã«åã®ã¿è¡¨ç¤ºãã¾ãã
# grep -ri john /home/users /home/users/subdir1/letter.txt:John, Thanks for your contribution. /home/users/name_list.txt:John Smith /home/users/name_list.txt:John Doe # grep -ril john /root /home/users/subdir1/letter.txt /home/users/name_list.txt