您的位置:首页 > 运维架构 > Linux

Linux在指定目录下查找包含指定字符串的文件

2013-03-21 16:05 691 查看
第一种方法:

#!/bin/bash

echo -e "\nThis is a program to find the file in special directory which include keyword!\n\n"

if [ "$1" == "" ]; then

echo -e "Please input the keyword behind the $0\.\n\n"

exit 0

fi

keyword=$1

dir=.

if [ "$2" != "" ]; then

dir=$2

fi

test ! -d $dir && echo -e "The $dir is not exist in your system\.\n\n" && exit 0

count=0

filelist=`ls -R $dir 2> /dev/null | grep -v '^$'`

for filename in $filelist

do

temp=`echo $filename | sed 's/:.*$//g'`

if [ "$filename" != "$temp" ]; then

curdir=$temp

#echo "current dir = $curdir"

else

filetype=`file $curdir/$filename | grep "text"`

if [ "$filetype" != "" ]; then

temp=`grep $keyword $curdir/$filename 2> /dev/null`

#echo $curdir/$filename

if [ "$temp" != "" ]; then

echo $curdir/$filename

count=$(($count+1))

fi

fi

fi

done

echo -e "\n\nTotal: $count"

echo -e "Done"

文件保存为myfind.sh

执行:chmod u+x myfind.sh

例如:

myfind.sh cs /home/zk

在/home/zk目录下查找包含cs的字符

第二种方法:

文件的查找

1. which (寻找『执行文件』)

# which [-a] command 参数: -a :列出所有可以找到的指令,默认是第一个被找到的指令。该指令是根据『PATH』这个环境变量所规范的路径,去搜寻执行文件名字。

2. whereis (寻找 【特定文件】 )

# whereis [-bmsu] 文件或目录名参数: -b :只找 binary 的文件 -m :只找在说明文件, manual 路径下的文件 -s :只找 source 来源文件 -u :没有说明文件的文件!

3.locate <文件名称>



 在文件索引数据库中搜索文件

4. find [路径] <表达式>

5.grep

目录中查询豆豆我最常用就是:grep -rm '查询字符串' /var/www/doudou



第三种方法:

whereis <程序名称>

  查寻software的安装路径

  -b 只查寻二进制文件

  -m 只查寻帮忙文件

  -s 只查寻源代码

  -u 排除指定类型文件

  -f 只预示文件名

  -B <目录> 在指定目录下查寻二进制文件

  -M <目录> 在指定目录下查寻帮忙文件

  -S <目录> 在指定目录下查寻源代码

locate <文件名称>

  在文件索引数据库中搜索文件

  -d <数据库路径> 搜索指定数据库

updatedb

  更新文件索引数据库

find [路径] <表达式>

  查寻文件

  -name <表达式> 按照文件名查寻文件

  -iname <表达式> 按照文件名查寻文件,忽略大小写

  -path <表达式> 按照路径查寻文件

  -ipath <表达式> 按照路径查寻文件,忽略大小写

  -amin <分钟> 过去N分钟内访问过的文件

  -atime <天数> 过去N天内访问过的文件

  -cmin <分钟> 过去N分钟内修改过的文件

  -ctime <天数> 过去N天内修改过的文件

  -anewer <参照文件> 比参照文件更晚被读取过的文件

  -cnewer <参照文件> 比参照文件更晚被修改过的文件

  -size <大小> 按照文件大小查寻文件,单位b c w k M G

  -type <文件类型> 按照文件类型查寻文件。b 块设备 c 字符设备 d 目录 p 管道文件 f 普通文件 l 链接 s 端口文件

  -user <用户名> 按归属用户查寻文件

  -uid <uid> 按UID查寻文件

  -group <群组名> 按归属群组查寻文件

  -gid <gid> 按GID查寻文件

  -empty 查寻具文件

从文件内容查寻匹配指定字符串的行:

  $ grep "被查寻的字符串" 文件名

从文件内容查寻与正则表达式匹配的行:

  $ grep –e “正则表达式” 文件名

查寻时不区分大小写:

  $ grep –i "被查寻的字符串" 文件名

查寻匹配的行数:

  $ grep -c "被查寻的字符串" 文件名

从文件内容查寻不匹配指定字符串的行:

  $ grep –v "被查寻的字符串" 文件名

从根目录开始查寻所有扩展名为.log的文本文件,并找出包罗”ERROR”的行

  find / -type f -name "*.log" | xargs grep "ERROR"

查寻到httpd.conf文件后即时在屏幕上预示httpd.conf文件信息。

  find/-name"httpd.conf"-ls

在根目录下查寻某个文件

  find . -name "test"

在某个目录下查寻包罗某个字符串的文件

  grep -r "zh_DN" ./

Others:

find .-type f /home/ews/dvlp/EWS_INSERT "*.log.*" |xargs grep -Hn "delete awsdyndb..EWS_SERV_PARA where ews_id in"
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐