Sai*_*Sai 2 unix bash shell find
场景:文件夹中有多个文件,我正在尝试查找特定的文件集,如果给定的文件有特定的信息,那么我需要grep信息.
例如:
find /abc/test \( -type f -name 'tst*.txt' -mtime -1 \) -exec grep -Po '(?<type1).*(?=type1|(?<=type2).*(?=type2)' {} \;
Run Code Online (Sandbox Code Playgroud)
我需要包括if条件和find -exec(如果grep为true则打印上面的内容)
if grep -q 'case=1' <filename>; then
grep -Po '(?<type1).*(?=type1|(?<=type2).*(?=type2)'
fi
Run Code Online (Sandbox Code Playgroud)
谢谢
您可以使用-execin find作为条件 - 如果命令返回成功的退出代码,则文件匹配.所以你可以写:
find /abc/test -type f -name 'tst*.txt' -mtime -1 -exec grep -q 'case=1' {} \; -exec grep -Po '(?<type1).*(?=type1|(?<=type2).*(?=type2)' {} \;
Run Code Online (Sandbox Code Playgroud)
测试find从左到右进行评估,因此grep只有在第一个测试成功时才执行第二次测试.
如果条件更复杂,可以将整个shell代码放入脚本中,然后执行脚本-exec.例如myscript.sh:
#!/bin/sh
if grep -q 'case=1' "$1"; then
grep -Po '(?<type1).*(?=type1|(?<=type2).*(?=type2)' "$1";
fi
Run Code Online (Sandbox Code Playgroud)
然后做:
find /abc/test -type f -name 'tst*.txt' -mtime -1 -exec ./myscript.sh {} \;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
154 次 |
| 最近记录: |