0

I have a file which has the following content:

10 tiny toes
tree
this is that tree
5 funny 0



There are spaces at the end of the file. I want to get the line number of the last row of a file (that has characters). How do I do that in SED?

Dudi Boy
  • 4,551
  • 1
  • 15
  • 30

4 Answers4

2

This is easily done with awk,

awk 'NF{c=FNR}END{print c}' file

With sed it is more tricky. You can use the = operator but this will print the line-number to standard out and not in the pattern space. So you cannot manipulate it. If you want to use sed, you'll have to pipe it to another or use tail:

sed -n '/^[[:blank:]]*$/!=' file | tail -1
kvantour
  • 25,269
  • 4
  • 47
  • 72
0

You can use following pseudo-code:

Replace all spaces by empty string
Remove all <beginning_of_line><end_of_line> (the lines, only containing spaces, will be removed like this)
Count the number of remaining lines in your file
Dominique
  • 16,450
  • 15
  • 56
  • 112
0

It's tough to count line numbers in sed. Some versions of sed give you the = operator, but it's not standard. You could use an external tool to generate line numbers and do something like:

nl -s ' ' -n ln -ba input | sed -n 's/^\(......\)...*/\1/p' | sed -n '$p'

but if you're going to do that you might as well just use awk.

William Pursell
  • 204,365
  • 48
  • 270
  • 300
0

This might work for you (GNU sed):

sed -n '/\S/=' file | sed -n '$p'

For all lines that contain a non white space character, print a line number. Pipe this output to second invocation of sed and print only the last line.

Alternative:

grep -n '\S' file | sed -n '$s/:.*//p'
potong
  • 55,640
  • 6
  • 51
  • 83