Shell脚本小工具

通过Shell实现在一个文件列表中搜索

2020-04-17  本文已影响0人  SpaceCat

经常会有这样的需求,有一个文件列表,需要在其中的每个文件中检查是否包含某个字符串。这里写一个Shell脚本实现的例子。
首先,创建测试文件,并写入内容:

$ cat a/a.txt 
This is a file for test.
$ cat a/anull.txt 
$ cat test.txt 
These violent delights have violent ends.
file completed.
$

将要搜索的文件路径列表写入到文件。注意,如果用相对路径,需要以脚本执行的目录为参考写相对路径,不然可能找不到文件。

$ cat filelist.txt 
a/a.txt
a/anull.txt
test.txt
$ 

写一个Shell脚本,读每一行,读取路径指示的文件,逐个搜索:

$ cat filelist.txt | while read tmpf
> do
> echo $tmpf
> grep -ir "file" $tmpf
> done
a/a.txt
a/a.txt:This is a file for test.
a/anull.txt
test.txt
test.txt:file completed.
$ 

也可以将上面的脚本写入到脚本文件:

$ cat test.sh
cat filelist.txt | while read tmpf
do
echo $tmpf
grep -ir "file" $tmpf
done
$ sh test.sh
a/a.txt
a/a.txt:This is a file for test.
a/anull.txt
test.txt
test.txt:file completed.
$

注意这里存放路径列表的文本文件中,要特别注意行分隔符。我在MacOS上通过自带的terminal进行验证,行分隔符为LF,也就是\n的时候,正常运行。如果行分隔符变成了CRLF,也就是\r\n,就会报错。如下:

$ sh test.sh 
a/a.txt
grep: a/a.txt\r: No such file or directory
a/anull.txt
grep: a/anull.txt\r: No such file or directory
test.txt
grep: test.txt\r: No such file or directory
$ 

如果行分隔符改成CR,也就是\r,运行效果就更诡异了,直接没有输出。如下:

$ sh test.sh 
$ 

这种shell中按行读的情况,运行有问题,一定要第一时间检查行分隔符,避免浪费时间!

上一篇下一篇

猜你喜欢

热点阅读