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

时间:2021-05-08 08:57:30

I have to find the 250th line of a txt file that does not have a comma using the grep command. The file has more than 250 lines, but I have to find to 250th line that does not.

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

Example:

例:

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. 

I used this command :

我用这个命令:

grep -vn "," test.txt

and then looked for the 250th line, but then I did the following command to see if the line numbers were the same, and they were.

然后寻找第250行,但后来我做了以下命令,看看行号是否相同,他们是。

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

I don't think this should be the case because the 250th line of the file without a comma should not be the same line as the 250th line of the regular file because the regular file has many lines with commas in them, so the line number should actually be less.

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

What is wrong here?

这有什么不对?

Thank you.

谢谢。

2 个解决方案

#1


1  

Unfortunately, posix disagrees:

不幸的是,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.)    
# ...

What you could do is toss some awk on:

你能做的就是扔一些awk:

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

#2


0  

Or you could try

或者你可以试试

grep -v , text.txt | head -250 | tail -1

#1


1  

Unfortunately, posix disagrees:

不幸的是,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.)    
# ...

What you could do is toss some awk on:

你能做的就是扔一些awk:

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

#2


0  

Or you could try

或者你可以试试

grep -v , text.txt | head -250 | tail -1