列出最后一行不包含模式的文件
List files whose last line doesn't contain a pattern
我文件的最后一行应该是“#”
如果我 tail -n 1 * | grep -L "#"
结果是 (standard input)
显然是因为它正在被管道传输。
希望有一个 grep 解决方案,而不是读取整个文件并只搜索最后一行。
你可以使用 sed
:
sed -n 'N;${/pattern/!p}' file
如果最后一行不包含模式,上述命令将打印 file
的所有行。
但是,看来我误会了你,你只想打印最后一行与模式不匹配的那些文件的文件名。在这种情况下,我会将 find
与以下 (GNU) sed
命令一起使用:
find -maxdepth 1 -type f -exec sed -n '${/pattern/!F}' {} \;
find命令遍历当前文件夹下的所有文件,执行sed
命令。 $
标记最后一行输入。如果 /pattern/
未找到 !
,则 F
打印文件名。
上面的解决方案看起来不错并且执行速度很快它有一个缺点它不会打印空文件的名称,因为最后一行永远不会到达并且$
将不匹配。
为了获得稳定的解决方案,我建议将命令放入脚本中:
script.sh
#!/bin/bash
# Check whether the file is empty ...
if [ ! -s "" ] ; then
echo ""
else
# ... or if the last line contains a pattern
sed -n '${/pattern/!F}' ""
# If you don't have GNU sed you can use this
# (($(tail -n1 a.txt | grep -c pattern))) || echo ""
fi
使其可执行
chmod +x script.sh
并使用以下 find
命令:
find -maxdepth 1 -type f -exec ./script.sh {} \;
for i in *; do tail -n 1 "$i" | grep -q -v '#' && echo "$i"; done
考虑一下这条线:
while read name ; do tail -n1 "$name" | grep -q \# || echo "$name" does not contain the pattern ; done < <( find -type f )
它使用 tail
获取每个文件的最后一行,并使用 grep
根据模式测试该行。许多文件的性能都不是最好的,因为每次迭代都会启动两个新进程。
我文件的最后一行应该是“#”
如果我 tail -n 1 * | grep -L "#"
结果是 (standard input)
显然是因为它正在被管道传输。
希望有一个 grep 解决方案,而不是读取整个文件并只搜索最后一行。
你可以使用 sed
:
sed -n 'N;${/pattern/!p}' file
如果最后一行不包含模式,上述命令将打印 file
的所有行。
但是,看来我误会了你,你只想打印最后一行与模式不匹配的那些文件的文件名。在这种情况下,我会将 find
与以下 (GNU) sed
命令一起使用:
find -maxdepth 1 -type f -exec sed -n '${/pattern/!F}' {} \;
find命令遍历当前文件夹下的所有文件,执行sed
命令。 $
标记最后一行输入。如果 /pattern/
未找到 !
,则 F
打印文件名。
上面的解决方案看起来不错并且执行速度很快它有一个缺点它不会打印空文件的名称,因为最后一行永远不会到达并且$
将不匹配。
为了获得稳定的解决方案,我建议将命令放入脚本中:
script.sh
#!/bin/bash
# Check whether the file is empty ...
if [ ! -s "" ] ; then
echo ""
else
# ... or if the last line contains a pattern
sed -n '${/pattern/!F}' ""
# If you don't have GNU sed you can use this
# (($(tail -n1 a.txt | grep -c pattern))) || echo ""
fi
使其可执行
chmod +x script.sh
并使用以下 find
命令:
find -maxdepth 1 -type f -exec ./script.sh {} \;
for i in *; do tail -n 1 "$i" | grep -q -v '#' && echo "$i"; done
考虑一下这条线:
while read name ; do tail -n1 "$name" | grep -q \# || echo "$name" does not contain the pattern ; done < <( find -type f )
它使用 tail
获取每个文件的最后一行,并使用 grep
根据模式测试该行。许多文件的性能都不是最好的,因为每次迭代都会启动两个新进程。