BOOKING

2018年6月7日星期四

linux 搜索文件,文件名,包含文字等等总结(不明白就死记硬背)

1)搜索一个文件中是否包含某特定字段:

grep -rl 'open' . --include=*.cpp

例如:搜索所有结尾是.cpp的文件内,是否包含open的字样。只要包含这个字样,就将文件名里出来,结果如下

./test/testall/file.cpp
./test/testall/shell_test.cpp
./test/daemontest/main.cpp



但是有时候只显示文件名,也不知道出现的地方到底是什么样子的,如果还有顺带查看一下那一行的内容,可以用如下命令

grep -rn 'open' . --include=*.cpp
则,执行结果如下:
./test/testall/file.cpp:270:    FILE *file = fopen(file_name.c_str(),"w");
./test/testall/file.cpp:273:            printf("Can't open the file\n");
./test/testall/shell_test.cpp:29:       FILE *file = fopen(file_name, "r");
./test/daemontest/main.cpp:53:  openlog("daemontest",LOG_PID,LOG_USER);
显示了文件名,行号以及该行内容。

2)使用find命令+grep
假设搜索所有的.cpp文件是否包含'open'字符串,如果包含了,则显示该文件,命令如下:
find -name '*.cpp' -exec grep -l 'open' {} \;
则结果如下:
./test/testall/file.cpp
./test/testall/shell_test.cpp
./test/daemontest/main.cpp
3) 搜索一个名称为 ‘*asd*’
sample :
find ./ -name '*asd*'

4) 搜索一个或者更多的字样 more than one sample.

find ./ -name '*asd*' -o -name '*bsc*'

5) 使用-size选项可以通过文件大小查找文件。 

查找比指定文件大的文件 
1
find ~ -size +100M
查找比指定文件小的文件 
1
find ~ -size -100M
查找符合给定大小的文件 
find ~ -size 100M


6) 通过和其他文件比较修改时间查找文件 显示在指定文件之后做出修改的文件。下面的find命令将显示所有的在ordinary_file之后创建修改的文件。 










ls -lrt
total 0
-rw-r----- 1 root root 0 2009-02-19 20:27 others_can_also_read
----r----- 1 root root 0 2009-02-19 20:27 others_can_only_read
-rw------- 1 root root 0 2009-02-19 20:29 ordinary_file
-rw-r--r-- 1 root root 0 2009-02-19 20:30 everybody_read
-rwxrwxrwx 1 root root 0 2009-02-19 20:31 all_for_all
---------- 1 root root 0 2009-02-19 20:31 no_for_all
# find -newer ordinary_file
.
./everybody_read
./all_for_all
./no_for_all
  

7) 查找5个最大的文件 下面的命令列出当前目录及子目录下的5个最大的文件。这会需要一点时间,取决于命令需要处理的文件数量。 


find . -type f -exec ls -s {} \; | sort -n -r | head -5


8) 查找5个最小的文件


方法同查找5个最大的文件类似,区别只是sort的顺序是降序。


find . -type f -exec ls -s {} \; | sort -n  | head -5
在root目录及其子目录下查找passwd文件。

1
2
3
4
5
# find / -name passwd
./usr/share/doc/nss_ldap-253/pam.d/passwd
./usr/bin/passwd
./etc/pam.d/passwd
./etc/passwd
在root目录及其1层深的子目录中查找passwd. (例如root — level 1, and one sub-directory — level 2)
?
1
2
# find -maxdepth 2 -name passwd
./etc/passwd


没有评论:

发表评论