分页: 1 / 2

在文本文件中查找字符串

发表于 : 2012-04-13 23:16
yuzifu
我有一个需求,对类型为文本的文件进行查找特定字符串,在网上找了一些资料,写了这么一个脚本:

代码: 全选

 #!/bin/sh
  
 if [ $# -ne 2 ]; then
     echo "Usage: txtstr path string"
     exit 1
 fi
 
 if [ ! -d "$1" ]; then
     echo "Input path not exist"
     exit 1
 fi
 
 find ${1} -type f |xargs -I {} sh -c 'file="{}";type=$(file $file);[[ $type=~"ASCII text" ]]&&echo $file' |xargs grep "${2}"
 
但是在使用的时候有时会出现问题。
如果文件名包含空格,则出错为:
No such file or directory

如果内容里包含',则出错为:
sh: -c: line 0: unexpected EOF while looking for matching ``'
sh: -c: line 1: syntax error: unexpected end of file

要怎么改这一段脚本呢,或者用其它什么办法可以达到需求呢。

Re: 在文本文件中查找字符串

发表于 : 2012-04-13 23:48
lilydjwg
二进制文件很碍事吗?

Re: 在文本文件中查找字符串

发表于 : 2012-04-14 8:27
fanhe
$file -> "$file"
试试

Re: 在文本文件中查找字符串

发表于 : 2012-04-14 10:36
cao627
:em11

代码: 全选

#!/bin/sh

 if [ $# -ne 2 ]; then
     echo "Usage: txtstr path string"
     exit 1
 fi

 if [ ! -d "$1" ]; then
     echo "Input path not exist"
     exit 1
 fi

file ${1} * | grep "ASCII text" | cut -d ":" -f1 | xargs grep "${2}"

Re: 在文本文件中查找字符串

发表于 : 2012-04-14 10:59
yuzifu
lilydjwg 写了:二进制文件很碍事吗?
文件不多的话没所谓。
若不是文本文件的话,会输出提示信息,而这个提示信息是不需要的。

Re: 在文本文件中查找字符串

发表于 : 2012-04-14 11:06
yuzifu
fanhe 写了:$file -> "$file"
试试
试过了,还是一样的效果。

Re: 在文本文件中查找字符串

发表于 : 2012-04-14 11:15
cao627

代码: 全选

xargs -0 grep "${2}"
试试行吗?

记得有个 -print0 和 xargs -0 的用法
不知道在这里怎么用?

Re: 在文本文件中查找字符串

发表于 : 2012-04-14 11:46
yuzifu
cao627 写了::em11

代码: 全选

#!/bin/sh

 if [ $# -ne 2 ]; then
     echo "Usage: txtstr path string"
     exit 1
 fi

 if [ ! -d "$1" ]; then
     echo "Input path not exist"
     exit 1
 fi

file ${1} * | grep "ASCII text" | cut -d ":" -f1 | xargs grep "${2}"
这段代码好像不能查找隐藏的文件,就是以点开头的文件。

Re: 在文本文件中查找字符串

发表于 : 2012-04-14 11:50
cao627
这段代码好像不能查找隐藏的文件,就是以点开头的文件。


怎么改?

Re: 在文本文件中查找字符串

发表于 : 2012-04-14 11:55
cao627

代码: 全选

ls -a  $1 | xargs file | grep "ASCII text" | cut -d ":" -f1   | xargs  grep "${2}" 
文件名含空格怎么解决还没想出来

Re: 在文本文件中查找字符串

发表于 : 2012-04-14 11:58
yuzifu
改成这样

代码: 全选

find ${1} -type f | xargs file | grep "ASCII text" | cut -d ":" -f1 | xargs grep ${2}

Re: 在文本文件中查找字符串

发表于 : 2012-04-14 12:19
cao627

代码: 全选

find ${1} -type f -print0 | xargs -0 grep ${2} | cut -d ":" -f1  
不如这样?

但cut 命令后 再加管道 过滤 "ASCII text" 空格文件名又有问题了

Re: 在文本文件中查找字符串

发表于 : 2012-04-14 12:31
yuzifu
我试了一下,这样好像可以。

代码: 全选

find ${1} -type f | xargs -i file {} | grep "ASCII text" | cut -d ":" -f1 | xargs -i grep -Hn ${2} {}

Re: 在文本文件中查找字符串

发表于 : 2012-04-14 12:43
cao627
yuzifu 写了:我试了一下,这样好像可以。

代码: 全选

find ${1} -type f | xargs -i file {} | grep "ASCII text" | cut -d ":" -f1 | xargs -i grep -Hn ${2} {}
好像是的!
学习!

Re: 在文本文件中查找字符串

发表于 : 2012-04-14 12:47
yuzifu
cao627 写了:
yuzifu 写了:我试了一下,这样好像可以。

代码: 全选

find ${1} -type f | xargs -i file {} | grep "ASCII text" | cut -d ":" -f1 | xargs -i grep -Hn ${2} {}
好像是的!
学习!
感谢您的帮助!