简体   繁体   English

检查bash文件的前N行是否包含字符串

[英]Check first N lines of bash file for string

I am trying to write a bash script that can go through and check only the first N lines of a file to match a specific string. 我正在尝试编写一个bash脚本,该脚本可以通过并仅检查文件的前N行以匹配特定的字符串。 I am able to write a simple command that will check the entire file, but information that is contained in lines greater than N may not be accurate. 我能够编写一个简单的命令来检查整个文件,但是大于N的行中包含的信息可能不准确。

Here is my current implementation 这是我当前的实现

find . -exec egrep -H -m 1 -l "\<$month/$day/$year\>" {} \;

I was thinking of using the head function to trim the files first but this does not seem to be working. 我当时在考虑使用head函数首先修剪文件,但这似乎不起作用。 Any suggestions? 有什么建议么? Thanks in advance 提前致谢

This will show you files matching the pattern in the first N lines 这将在前N行显示与该模式匹配的文件

find . -type f | xargs egrep -H -m 1 -n "\<$month/$day/$year\>" | awk -F : '$2 <= N { print $1; }'

egrep searches for the first occurrence in a file and adds a line number. egrep搜索文件中的第一个匹配项并添加行号。 awk then searches for all lines with a line number less or equal to N (insert number here) and prints the filename. 然后, awk搜索行号小于或等于N (在此插入号)的所有行并打印文件名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM