In this question Get line number from character position I know that it is possible to, in a text file, get the line number from a character position using scripts.

Emacs has a functionality M-x-goto-char that positions the cursor in the character position.

My question is: Are there any UNIX utilities that composed could get the work done in an elegant way?


The same technique can be used with standard POSIX tools: count the number of lines up to the character position you’re interested in.

One way to do this is to use dd to keep the characters up to the position of interest, and wc to count the lines:

dd if=input bs=1 count=5437 | wc -l

This counts lines starting from 0 (i.e. if wc -l outputs 0, the character occurs on the first line).

The following variant cleans the output up and starts from 1:

(dd if=input bs=1 count=5437 2>/dev/null; printf "\n") | wc -l
  • I don't have emacs. Any idea if emacs goto-char includes newlines in the count? I know that dd would include newlines in count=5437
    – iruvar
    Dec 19 '19 at 16:18
  • @iruvar goto-char counts newlines too, the results would be identical here. Dec 19 '19 at 17:10
  • This counts the newline at the end of line N as belonging to line N + 1.  To get the more standard interpretation (a newline belongs to the line it ends), subtract one from the byte count; e.g., use count=5436 to identify the line containing the 5437th character. … … … … … … … Unless you’re counting characters starting at 0, in which case you should say so. … … … … P.S. The original Stack Overflow question actually uses 5347, not 5437. Dec 30 '19 at 2:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.