InfraPlatform

[Bash Shellscript 기본다지기] 파일 관리 ( find , wc , grep ) : 중.상급

IT오이시이 2014. 6. 16. 11:05
728x90

[Bash Shellscript 기본다지기]  파일 관리 ( find , wc , grep ) : 중.상급

1. 디렉토리 아래 파일 들의 개수를 카운팅 하는 셀 스크립트를 작성 하시오

   ( find , wc  활용)

2. 다음과 같은 디렉토리를 생성하여  각 폴더마다 10개의 파일을 생성 하시오

    (단.  각 파일의 내용은 명령이 수행된 시점의 ps  -ef 의 내용을 저장합니다.)

      100/1/1001.txt

      100/2/1002.txt

      100/3/1003.txt

      100/4/1004.txt

            .. 중략 ...

      100/99/1099.txt

3. 파일중  현재 기준 30일 이전에 만들어진 파일 찾는 스크립트를 작성하시오.




과제 해설

1. 디렉토리 아래 파일 들의 개수를 카운팅 하는 셀 스크립트를 작성 하시오

$ find . -type f | wc -l

   find . 명령으로 현재 경로 하위의 파일 개수를 찾는 것

    wc  ( word count  ) 명령으로  파일의 라인수를 찾는다.


2. 다음과 같은 디렉토리를 생성하여  각 폴더마다 10개의 파일을 생성 하시오



  1) 기능별 함수를 만들었다.

2) 셀을 만들고 실행테스트를 위해서 echo를 이용한 부분을 숙지하자.

3) ps -ef 를 수행한 이유를 잘 알아야 한다.

각 프로세스가 빠르게 수행되면서 fork 되는 프로세스를 확인하자..

ps 대신 pstree 도 좋다.


# 4.th mkdir path


function make_dirs {


 dname="$1/$2"

 echo "    mkdir -p $dname "

mkdir -p $dname

 ls -al $dname


}

function write_file {

  for cnt in {1..10}

  do

      fname="$1/$2/$1$2$cnt.txt"

      echo "       ps -ef > $fname"

pstree -p > $fname

  done

}



for path1 in {1..100}

do


    for path2 in {1..10}

    do

        make_dirs  $path1 $path2;

        write_file $path1 $path2;

    done


done


[실행결과]

   mkdir -p 100/9

      ps -ef > 100/9/10091.txt

      ps -ef > 100/9/10092.txt

      ps -ef > 100/9/10093.txt

      ps -ef > 100/9/10094.txt

      ps -ef > 100/9/10095.txt

      ps -ef > 100/9/10096.txt

      ps -ef > 100/9/10097.txt

      ps -ef > 100/9/10098.txt

      ps -ef > 100/9/10099.txt

      ps -ef > 100/9/100910.txt

   mkdir -p 100/10

      ps -ef > 100/10/100101.txt

      ps -ef > 100/10/100102.txt

      ps -ef > 100/10/100103.txt

      ps -ef > 100/10/100104.txt

      ps -ef > 100/10/100105.txt

      ps -ef > 100/10/100106.txt

      ps -ef > 100/10/100107.txt

      ps -ef > 100/10/100108.txt

      ps -ef > 100/10/100109.txt

      ps -ef > 100/10/1001010.txt


> sshd(1760)--sshd(20470)---sshd(20472)----bash(20473)-----pstree(23415)


3. 파일중  현재 기준 30일 이전에 만들어진 파일 찾는 스크립트를 작성하시오.

$ find . -mtime +30 -type f -ls

-ctime  -mtime 를 같이 활용 하는데 ctime create time 이 아니라는 것이 함정이다.

ctime     File’s status was last changed n*24 hours ago

mtime   File’s data was last modified n*24 hours ago.


$  stat /bin/ls

 File: `/bin/ls'

 Size: 117024          Blocks: 232        IO Block: 4096   regular file

Device: 802h/2050d      Inode: 131104      Links: 1

Access: (0755/-rwxr-xr-x)  Uid: (    0/    root)   Gid: (    0/    root)

Access: 2013-12-09 03:45:03.294019014 +0900

Modify: 2013-11-23 00:36:45.000000000 +0900

Change: 2013-12-06 16:46:45.159063663 +0900


[iparkm@dev1 ~]$ find . -ctime +30 -type f -ls | wc -l

11866

[iparkm@dev1 ~]$ find . -mtime +30 -type f -ls | wc -l

15086

참고 자료

$ find --help


Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec] [path...] [expression]


default path is the current directory; default expression is -print

expression may consist of: operators, options, tests, and actions:


-P     Never  follow  symbolic links.

-L     Follow  symbolic  links.

-H     Do  not  follow  symbolic links

-D    debugoptions

        help   Explain the debugging options

        tree   Show the expression tree in its original

        stat   Print  messages  as  files  are  examined with the stat and lstat

        opt    Prints diagnostic  information  relating  to  the  optimisation  of  the

                expression tree; see the -O option.

      rates  Prints  a  summary  indicating  how  often  each  predicate succeeded or

                failed.


-Olevel

    0      Equivalent to optimisation level 1.

    1      This  is  the  default  optimisation level and corresponds to the tradi-

                    tional behaviour.

    2      Any  -type  or  -xtype tests are performed after any tests based only on

                    the names of files,

    3      At  this  optimisation  level,




operators (decreasing precedence; -and is implicit where no others are given):

     ( EXPR )   ! EXPR   -not EXPR   EXPR1 -a EXPR2   EXPR1 -and EXPR2

     EXPR1 -o EXPR2   EXPR1 -or EXPR2   EXPR1 , EXPR2


positional options (always true): -daystart -follow -regextype


normal options (always true, specified before other expressions):

     -depth --help -maxdepth LEVELS -mindepth LEVELS -mount -noleaf

     --version -xdev -ignore_readdir_race -noignore_readdir_race


-maxdepth levels

-mindepth levels

-regextype type      

                   -regex  and  -iregex

-warn, -nowarn



tests (N can be +N or -N or N): -amin N -anewer FILE -atime N -cmin N

     -cnewer FILE -ctime N -empty -false -fstype TYPE -gid N -group NAME

     -ilname PATTERN -iname PATTERN -inum N -iwholename PATTERN -iregex PATTERN

     -links N -lname PATTERN -mmin N -mtime N -name PATTERN -newer FILE

     -nouser -nogroup -path PATTERN -perm [+-]MODE -regex PATTERN

     -readable -writable -executable

     -wholename PATTERN -size N[bcwkMG] -true -type [bcdpflsD] -uid N

     -used N -user NAME -xtype [bcdpfls]

     -context CONTEXT

-false                : Always false.


[파일 시스템 속성]

-newer  file       :

-newerXY reference

             a   The access time of the file reference

             B   The birth time of the file reference

             c   The inode status change time of reference

             m   The modification time of the file reference

             t   reference is interpreted directly as a time


-cnewer file      :

-anewer file     : File was last accessed more recently than file was modified.

-amin n            : File was last accessed n minutes ago. ( amin, cmin, mmin )

-atime n           : File was last accessed n*24 hours ago.

-used n            : File was last accessed n days after its status was last changed.


-empty             : File is empty and is either a regular file or a directory.

-executable      : executable and directories which are searchable


-fstype type      : nfs,  tmp,  mfs, S51K, S52K.

-gid n                : File’s numeric group ID is n.

-group gname  :

-perm mode     :    -perm  g=w

-size n[cwbkMG]

-samefile name  : File refers to the same inode as name. When -L is in effect,


[match]

-name pattern  :  matches shell  pattern  pattern  (‘*’, ‘?’, and ‘[]’)

-path pattern    :  File  name  matches shell pattern pattern.

                           find . -path "./sr*sc"

                           find bar -path /foo/bar/myfile -print

-regex pattern

-iname pattern :  match is case insensitive

-ipath pattern   : same way as -iwholename.  This option is deprecated, do not use it.

-iregex pattern  : Like -regex, but the match is case insensitive.



-type c

             File is of type c:

             b      block (buffered) special

             c      character (unbuffered) special

             d      directory

             p      named pipe (FIFO)

             f      regular file

             l      symbolic link; this is never true if the -L option or the -follow option

                    is in effect, unless the symbolic link is broken.  If you want to search

                    for symbolic links when -L is in effect, use -xtype.

             s      socket

             D      door (Solaris)




actions: -delete -print0 -printf FORMAT -fprintf FILE FORMAT -print

     -fprint0 FILE -fprint FILE -ls -fls FILE -prune -quit

     -exec COMMAND ; -exec COMMAND {} + -ok COMMAND ;

     -execdir COMMAND ; -execdir COMMAND {} + -okdir COMMAND ;


-delete   :  Delete  files; true if removal succeeded.


-exec command ;  (with a ‘\’) or  quoted  to  protect  them  from expansion  by  the  shell.


-fprint    file

-fprintf   file format   :

-fprint0  file              :


-ok command ; Like  -exec but ask the user first.

-okdir command ;

-printf format      

          \b        Backspace.

          \c        Stop printing from this format

          %Ak    File’s  last  access  time in the format specified by k,

           %b     The amount of disk space used for this file in  512-byte  blocks.

           %c     File’s  last  status change time

           %d     File’s  depth  in the directory tree;


            -prune True;  if  the file is a directory, do not descend into it.

            -quit  Exit  immediately.


find . -type f -exec file '{}' \;

find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f             

find / \( -perm -4000 -fprintf /root/suid.txt '%#m %u %p\n' \) , \

        \( -size +100M -fprintf /root/big.txt '%-10s %p\n' \)

find /sbin /usr/sbin -executable \! -readable -print

      find . -perm -664

      find . -perm /220

      find . -perm /u+w,g+w

      find . -perm /u=w,g=w



 

Report (and track progress on fixing) bugs via the findutils bug-reporting

page at http://savannah.gnu.org/ or, if you have no web access, by sending

email to <bug-findutils@gnu.org>.






find  기본 명령

find  [path] [expression]

 find . -type f

find 확장 명령

find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec] [path...] [expression]



** wc는 아주 간단한 프로그램이지만 

  약방의 감초처럼 아무데서나 사용을 하는 것이라 옵션을 모두 알아 두자

$ wc --help

Usage: wc [OPTION]... [FILE]...

 or:  wc [OPTION]... --files0-from=F

Print newline, word, and byte counts for each FILE, and a total line if

more than one FILE is specified.  With no FILE, or when FILE is -,

read standard input.

 -c, --bytes            print the byte counts

 -m, --chars            print the character counts

 -l, --lines            print the newline counts

     --files0-from=F    read input from the files specified by

                          NUL-terminated names in file F;

                          If F is - then read names from standard input

 -L, --max-line-length  print the length of the longest line

 -w, --words            print the word counts

     --help     display this help and exit

     --version  output version information and exit


Report wc bugs to bug-coreutils@gnu.org

GNU coreutils home page: <http://www.gnu.org/software/coreutils/>

General help using GNU software: <http://www.gnu.org/gethelp/>

For complete documentation, run: info coreutils 'wc invocation'



728x90
반응형