Linux基础命令--grep/find

1、定义一个对所有用户都生效的命令别名,例如:lftps=‘lftp 172.168.0.1/pub’

    在/etc/profile.d/目录下创建文件alias_glob.sh,添加一下代码:

alias lftps=‘lftp 172.168.0.1/pub’

    添加后保存退出,立即生效命令:

source /etc/profile.d/alias_glob.sh

2、显示/etc/passwd文件中不以/bin/bash结尾的行

grep -v '/bin/bash' /etc/passwd

3、找出/etc/passwd文件中,包含二位数字或者三位数的行

[root@localhost profile.d]# grep "\<[0-9]\{2,3\}\>" /etc/passwd

4、显示/proc/meminfo文件中以大写或小写S开头的行;用三种方式实现。

第一种:[root@localhost profile.d]# grep "^[sS]" /proc/meminfo
第二种:[root@localhost profile.d]# grep -E "^(s|S)" /proc/meminfo
第三种:[root@localhost profile.d]# grep  -i "^s" /proc/meminfo

5、使用echo输出一个绝对路径,使用egrep取出路径名,类似执行dirname /etc/passwd的结果。

[root@localhost profile.d]# echo /etc/sysconfig/.etwork-scripts | egrep -o ".*/[^/ ]" | egrep -o ".*/" | egrep -o ".*[^/]"

6、找出ifconfig中的ip地址。要求结果只显示IP地址;

[root@localhost profile.d]# ifconfig | grep "inet" | head -1 |grep -Eo "inet (addr :)?([0-9]*\.){3}[0-9]*" | grep -Eo '([0-9]*\.){3}[0-9]*'

7、VIM定制自动缩进四个字符。

编辑vim配置文件:
    vim /etc/vim/vimrc 
在文件最后加入以下行:
    set shiftwidth=4

8、编写脚本,实现自动添加三个用户,并计算三个用户的uid之和。

#!/bin/bash                                          
#                                                    
#[ $# -ne 3 ] && echo "Args must be 3" && exit       
id $1 &> /dev/null && echo "$1 exists"  || useradd $1
id $2 &> /dev/null && echo "$2 exists"  || useradd $2
id $3 &> /dev/null && echo "$3 exists"  || useradd $3
                                                     
                                                     
ID1=$(id $1 -u)                                      
ID2=$(id $2 -u)                                      
ID3=$(id $3 -u)                                      
                                                     
sumid=$[ID1+ID2+ID3]                                 
echo $sumid

9、find用法及常用用法的实例演示。

Linux中find常见用法示例
#find  path  -option  [  -print ]  [ -exec  -ok  command ]  {} \;

#-print 将查找到的文件输出到标准输出
#-exec  command  {} \;     —–将查到的文件执行command操作,{} 和 \;之间有空格。其实在命令执行的时候"{}"将被find到的结果替换掉,因此将"{}"看成find到的文件来进行操作就很容易理解这个选项了。
#-ok 和-exec相同,只不过在操作前要询用户
====================================================
-name  filename             #查找名为filename的文件
-iname filename             #查找名为filename的文件,忽略大小写(case insensitive)
-perm  XXX                  
       -ugo=rwx             按执行权限来查找
-user   username            #按文件属主来查找
-group groupname            #按组来查找
-mtime  -n +n               #按文件更改时间来查找文件,-n指n天以内,+n指n天以前
-atime   -n +n              #按文件访问时间来查GIN: 0px">-perm                      
-user   username            #按文件属主来查找
-group groupname            #按组来查找
-mtime  -n +n               #按文件更改时间来查找文件,-n指n天以内,+n指n天以前
-atime   -n +n              #按文件访问时间来查找文件,-n指n天以内,+n指n天以前
-ctime   -n +n              #按文件创建时间来查找文件,-n指n天以内,+n指n天以前
-nogroup                    #查找无有效属组的文件,即文件的属组在/etc/groups中不存在
-nouser                     #查找无有效属主的文件,即文件的属主在/etc/passwd中不存
-newer  file                #查找修改时间比file更近的文件
-newer  f1 !f2              #查更改时间比f1新但比f2旧的文件
-ctime   -n +n              #按文件创建时间来查找文件,-n指n天以内,+n指n天以前
-nogroup                    #查无有效属组的文件,即文件的属组在/etc/groups中不存在
-nouser                     #查无有效属主的文件,即文件的属主在/etc/passwd中不存
-type    b/d/c/p/l/f        #查是块设备、目录、字符设备、管道、符号链接、普通文件
-size     n[c/w/k/M/G]      #查长度为n块[或n字节]的文件
                           `b'    for 512-byte blocks (this is the default if no suffix is used)
                           `c'    for bytes
                           `w'    for two-byte words
                           `k'    for Kilobytes (units of 1024 bytes)
                           `M'    for Megabytes (units of 1048576 bytes)
                           `G'    for Gigabytes (units of 1073741824 bytes)

-depth                      #使查找在进入子目录前先行查找完本目录
-maxdepth n                 #指定查找目录最大深度
-mindepth n                 #指定查找目录最小深度
-fstype                     #查位于某一类型文件系统中的文件,这些文件系统类型通常可在/etc/fstab中
                             找到
-mount                      #查文件时不跨越文件系统mount点
-follow                     #如果遇到符号链接文件,就跟踪链接所指的文件
-mount                      #查文件时不跨越文件系统mount点
-cpio                       #对匹配的文件使用cpio命令,将他们备份到磁带设备中
-prune                      #忽略某个目录
-inum                       #通过inode码查找文件
 
============================以下英文部分摘自find man手册==========================================
   OPERATORS
       Listed in order of decreasing precedence:
       ( expr )
              Force  precedence.   Since  parentheses  are special to the shell, you
              will normally need to quote them.  Many of the examples in this manual
              page use backslashes for this purpose: `\(...\)' instead of `(...)'.
       ! expr True  if expr is false.  This character will also usually need protec‐
              tion from interpretation by the shell.
       -not expr
              Same as ! expr, but not POSIX compliant.
       expr1 expr2
              Two expressions in a row are taken to be joined with an implied "and";
              expr2 is not evaluated if expr1 is false.
       expr1 -a expr2
              Same as expr1 expr2.
       expr1 -and expr2
              Same as expr1 expr2, but not POSIX compliant.
       expr1 -o expr2
              Or; expr2 is not evaluated if expr1 is true.
       expr1 -or expr2
              Same as expr1 -o expr2, but not POSIX compliant.
       expr1 , expr2
              List;  both  expr1 and expr2 are always evaluated.  The value of expr1
              is discarded; the value of the list is the value of expr2.  The  comma
              operator  can  be  useful for searching for several different types of
              thing,  but  traversing  the  filesystem  hierarchy  only  once.   The
              -fprintf  action  can  be  used to list the various matched items into
              several different output files.
 
=====================================示   例===========================================
$find  ~  -name  "*.txt"  -print          #在$HOME中查.txt文件并显示
$find  .   -name  "*.txt"  -print
$find  /etc  -name  "host*"  -print       #查以host开头的文件
$find  .  -name  "[a-z][a-z][0–9][0–9].txt" -print  #查以两个小写字母和两个数字开头
                                                       的txt文件
$find .  -perm  755  -print
$find  .  -perm -007  -exec ls -l {} \;  #查所有用户都可读写执行的文件同-perm 777
$find  .  -size  +1000000c  -print       #查长度大于1Mb的文件
$find  .  -size  100c        -print      # 查长度为100c的文件
$find  .  -size  +10  -print             #查长度超过10块的文件(1块=512字节)
$find  /etc -name "passwd*"  -exec grep  "cnscn"  {}  \;  #看是否存在cnscn用户
======================================================
find  -name april*                      在当前目录下查找以april开始的文件
find  -name  april*  fprint file        在当前目录下查找以april开始的文件,并把结果输出到
                                         file中
find  -name ap* -or -name may*          查找以ap或may开头的文件
find  /mnt  -name tom.txt  -fstype vfat 在/mnt下查找名称为tom.txt且文件系统类型为vfat的
                                         文件
find  /mnt  -name t.txt ! -fstype vfat  在/mnt下查找名称为tom.txt且文件系统类型不为vfat
                                          的文件
find  /tmp  -name wa* -type l           在/tmp下查找名为wa开头且类型为符号链接的文件
find  /home  -mtime  -2                 在/home下查最近两天内改动过的文件
find /home   -atime -1                  查1天之内被访问过的文件
find /home -mmin   +60                  在/home下查60分钟前改动过的文件
find /home  -amin  +30                  查最近30分钟前被访问过的文件
find /home  -newer  tmp.txt             在/home下查更新时间比tmp.txt近的文件或目录
find /home  -anewer  tmp.txt            在/home下查访问时间比tmp.txt近的文件或目录
find  /home  -used  -2                  列出文件或目录被改动过之后,在2日内被访问过的文件
                                          或目录
find  /home  -user cnscn                列出/home目录内属于用户cnscn的文件或目录
find  /home  -uid  +501                 列出/home目录内用户的识别码大于501的文件或目录
find  /home  -group  cnscn              列出/home内组为cnscn的文件或目录
find  /home  -gid 501                   列出/home内组id为501的文件或目录
find  /home  -nouser                    列出/home内不属于本地用户的文件或目录
find  /home  -nogroup                   列出/home内不属于本地组的文件或目录
find  /home  -name tmp.txt -maxdepth 4  列出/home内的tmp.txt 查时深度最多为3层
find  /home  -name tmp.txt -mindepth 3  从第2层开始查
find / -mindepth 3 -maxdepth 5 -name txt在根目录的第2级和第4级之间查找 
find  /home  -empty                     查找大小为0的文件或空目录
find  /home  -size  +512k               查大于512k的文件
find  /home  -size  -512k               查小于512k的文件
find  /home  -links  +2                 查硬连接数大于2的文件或目录
find  /home  -perm  0700                查权限为700的文件或目录
find  /tmp  -name tmp.txt  -exec cat {} \;查找并打印tmp.txt
find  /tmp  -name  tmp.txt  -ok  rm {} \;查找并删除tmp.txt,删除之前确认
 
=======================================================================
查找当前目录中的所有htm文件,并将其改名为html文件。
find . -name "*.htm" -exec mv {} {}l \;
=============================================================================
在/logs目录中查找更改时间在5日以前的文件并删除它们:
$ find logs -type f -mtime +5 -exec  -ok  rm {} \;
============================================================================
查询当天修改过的文件
# find  ./  -mtime  -1  -type f  -exec  ls -l  {} \;
============================================================================
查询文件并询问是否要显示
[root@book class]# find  ./  -mtime  -1  -type f  -ok  ls -l  {} \; 
============================================================================
Create Alias for Frequent Find Operations
  If you find some thing as pretty useful, then you can make it as an alias. And execute it whenever you want.

Remove the files named a.out frequently.
# alias rmao="find . -iname a.out -exec rm {} /;"
# rmao
============================================================================
使用find查找文件的时候怎么避开某个文件目录
比如要在/usr/sam目录下查找不在dir1子目录之内的所有文件
find /usr/sam -path "/usr/sam/dir1" -prune -o -print
 
  -prune  if the file is a directory, do not descend into(落进,降到…里) it.
 
find path [-path ..] [expression] 在路径列表的后面的是表达式
-path "/usr/sam" -prune -o -print 是 -path "/usr/sam" -a -prune -o -print 的简写表达式,按顺序求值, -a 和 -o 都是短路求值,与 shell 的 && 和 || 类似如果 -path "/usr/sam" 为真,则求值 -prune , -prune 返回真,与逻辑表达式为真;否则不求值 -prune,与逻辑表达式为假。如果 -path "/usr/sam" -a -prune 为假,则求值 -print ,-print返回真,或逻辑表达式为真;否则不求值 -print,或逻辑表达式为真。
 
这个表达式组合特例可以用伪码写为
if -path "/usr/sam"  then
          -prune
else
          -print
 
避开多个文件夹
find /usr/sam \( -path /usr/sam/dir1 -o -path /usr/sam/file1 \) -prune -o -print
圆括号表示表达式的结合。\ 表示引用,即指示 shell 不对后面的字符作特殊解释,而留给 find 命令去解释其意义。
查找某一确定文件,-name等选项加在-o 之后
find /usr/sam  \(-path /usr/sam/dir1 -o -path /usr/sam/file1 \) -prune -o -name "temp" -print
==================================================================================================
find + xargs
xargs
xargs - build and execute command lines from standard input
    在使用find命令的-exec选项处理匹配到的文件时, find命令将所有匹配到的文件一起传递给exec执行。但有些系统对能够传递给exec的命令长度有限制,这样在find命令运行几分钟之后,就会出现溢出错误。错误信息通常是“参数列太长”或“参数列溢出”。这就是xargs命令的用处所在,特别是与find命令一起使用。
    find命令把匹配到的文件传递给xargs命令,而xargs命令每次只获取一部分文件而不是全部,不像-exec选项那样。这样它可以先处理最先获取的一部分文件,然后是下一批,并如此继续下去。
    在有些系统中,使用-exec选项会为处理每一个匹配到的文件而发起一个相应的进程,并非将匹配到的文件全部作为参数一次执行;这样在有些情况下就会出现进程过多,系统性能下降的问题,因而效率不高;而使用xargs命令则只有一个进程。另外,在使用xargs命令时,究竟是一次获取所有的参数,还是分批取得参数,以及每一次获取参数的数目都会根据该命令的选项及系统内核中相应的可调参数来确定。
    来看看xargs命令是如何同find命令一起使用的,并给出一些例子。
下面的例子查找系统中的每一个普通文件,然后使用xargs命令来测试它们分别属于哪类文件
#find . -type f -print | xargs file
./.kde/Autostart/Autorun.desktop: UTF-8 Unicode English text
./.kde/Autostart/.directory:      ISO-8859 text\
......
在整个系统中查找内存信息转储文件(core dump) ,然后把结果保存到/tmp/core.log 文件中:
$ find / -name "core" -print | xargs echo "" >/tmp/core.log
上面这个执行太慢,我改成在当前目录下查找
#find . -name "file*" -print | xargs echo "" > /temp/core.log
# cat /temp/core.log
./file6
在当前目录下查找所有用户具有读、写和执行权限的文件,并收回相应的写权限:
# ls -l
drwxrwxrwx    2 sam      adm          4096 10月 30 20:14 file6
-rwxrwxrwx    2 sam      adm             0 10月 31 01:01 http3.conf
-rwxrwxrwx    2 sam      adm             0 10月 31 01:01 httpd.conf

# find . -perm -7 -print | xargs chmod o-w
# ls -l
drwxrwxr-x    2 sam      adm          4096 10月 30 20:14 file6
-rwxrwxr-x    2 sam      adm             0 10月 31 01:01 http3.conf
-rwxrwxr-x    2 sam      adm             0 10月 31 01:01 httpd.conf
用grep命令在所有的普通文件中搜索hostname这个词:
# find . -type f -print | xargs grep "hostname"
./httpd1.conf:#     different IP addresses or hostnames and have them handled by the
./httpd1.conf:# VirtualHost: If you want to maintain multiple domains/hostnames
on your
用grep命令在当前目录下的所有普通文件中搜索hostnames这个词:
# find . -name \* -type f -print | xargs grep "hostnames"
./httpd1.conf:#     different IP addresses or hostnames and have them handled by the
./httpd1.conf:# VirtualHost: If you want to maintain multiple domains/hostnames
on your
注意,在上面的例子中, \用来取消find命令中的*在shell中的特殊含义。
find命令配合使用exec和xargs可以使用户对所匹配到的文件执行几乎所有的命令。

猜你喜欢

转载自blog.51cto.com/12686444/2324934
今日推荐