user2615699
user2615699

Reputation:

finding line number of file using grep command Linux

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.

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.

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.

What is wrong here?

Thank you.

Upvotes: 0

Views: 1646

Answers (2)

MichaelMilom
MichaelMilom

Reputation: 3067

Or you could try

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

Upvotes: 0

phs
phs

Reputation: 11061

Unfortunately, posix disagrees:

$ 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:

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

Upvotes: 1

Related Questions