linux - 使用 grep 命令 Linux 查找文件的行号

标签 linux grep

我必须使用 grep 命令找到没有逗号的 txt 文件的第 250 行。该文件有超过 250 行,但我必须找到第 250 行没有。

例子:

Imagine you had a 10 line file and you were looking for the 3rd line that did not contain a comma

Lines 1 and 2 do not have a comma 
lines 3-7 have a comma
Line 8 does not contain a comma 

The answer for this file would be line 8. 

我使用了这个命令:

grep -vn "," test.txt

然后查找第 250 行,但随后我执行了以下命令以查看行号是否相同,结果确实如此。

grep -n "this is text from the 250th line"  test.txt 

我不认为应该是这种情况,因为文件的第 250 行 没有 不应该与常规文件的第 250 行在同一行,因为常规文件有很多行中有逗号,所以行号实际上应该更少。

这里有什么问题吗?

谢谢。

最佳答案

不幸的是,posix 不同意:

$ man grep
# ...
-n, --line-number
  Prefix each line of output with the 1-based line number within its input file.  (-n is specified by POSIX.)    
# ...

你可以做的是将一些 awk 放在:

$ grep -v , text.txt | awk '{ if (NR == 250) { print } }'

关于linux - 使用 grep 命令 Linux 查找文件的行号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21593038/

相关文章:

php - 限制服务器访问

linux - 使用 chkservd 的 cassandra nosql 自动重启服务

windows - 如何编写正则表达式来重复捕获较大匹配中的组?

python - 搜索大tar.gz文件中的关键字,复制并删除

linux - 比较一组词的出现

php - 为什么我的服务器要加载这些 PHP 变量?

linux - 在 ubuntu 16.04 上从 Java 1.8.0_111 降级到 1.8.0_102?

javascript - HTML 使用 JS 打印页面

awk - 使用 grep 或 awk 搜索列并存储在变量中

linux - 获取 linux 中单词倒数第二个出现的行