# Linux Shell 文本处理

# find 文件查找

# 查找txt和pdf文件

find . ( -name "*.txt" -o -name "*.pdf" ) -print

# 正则方式查找.txt和pdf

find . -regex  ".*(.txt|.pdf)$"

# 否定参数查找所有非txt文本

find . ! -name "*.txt" -print

# 指定搜索深度打印出当前目录的文件(深度为1)

find . -maxdepth 1 -type f

# 定制搜索

# 按类型搜索:

find . -type d -print  //只列出所有目录
-type f 文件 / l 符号链接

# 按时间搜索:-atime 访问时间 (单位是天,分钟单位则是-amin,以下类似)-mtime 修改时间 (内容被修改)-ctime 变化时间 (元数据或权限变化)

# 最近7天被访问过的所有文件:

find . -atime 7 -type f -print

# 按大小搜索:w字 k M G寻找大于2k的文件

find . -type f -size +2k

# 按权限查找:

find . -type f -perm 644 -print //找具有可执行权限的所有文件

# 按用户查找:

find . -type f -user weber -print// 找用户weber所拥有的文件

# 找到后的后续动作

# 删除:删除当前目录下所有的swp文件:

find . -type f -name "*.swp" -delete

# 执行动作(强大的exec)

find . -type f -user root -exec chown weber {} ; //将当前目录下的所有权变更为weber
##注:{}是一个特殊的字符串,对于每一个匹配的文件,{}会被替换成相应的文件名;
##eg:将找到的文件全都copy到另一个目录:
find . -type f -mtime +10 -name "*.txt" -exec cp {} OLD ;

# 结合多个命令tips: 如果需要后续执行多个命令,可以将多个命令写成一个脚本。然后 -exec 调用时执行脚本即可;

-exec ./commands.sh {} \;

# grep 文本搜索

# grep match_patten file // 默认访问匹配行

# 常用参数-o 只输出匹配的文本行 VS -v 只输出没有匹配的文本行-c

# 统计文件中包含文本的次数

grep -c "text" filename
-n 打印匹配的行号
-i 搜索时忽略大小写
-l 只打印文件名

# 在多级目录中对文本递归搜索(程序员搜代码的最爱):

grep "class" . -R -n

# 匹配多个模式

grep -e "class" -e "vitural" file

# grep输出以作为结尾符的文件名:(-z)

grep "test" file* -lZ| xargs -0 rm

# 转载地址 (opens new window)