3

I have a file which contain 64895 characters

In [95]: !wc -c 07.org                 
64895 07.org

How could I get the character at position 60000?

  • oh question: does the file have ascii? have newlines? My answer expects ascii and no newlines. – Rinzwind Nov 19 at 8:00
  • 1
    note that wc -c reports the number of bytes rather than the number of characters – steeldriver Nov 19 at 8:09
5

There is the cut command for that:

tr -d '\n' <  07.org | cut -c60000 

The 1st part removes newlines; the 2nd part then prints the 60000th char (but does skip the newline char so if those need to be included in the count towards 60000 this wont work ;) )

  • amazing and interesting, the text visualble at position less than 60000, and the char at 60000 push the command line to the bottom and clear up the screen. – Algebra Nov 19 at 8:06
  • That's cuz you have newlines in the file. What this does is print 1 char -per- line and lines shorter than 60000 ... are an empty line. Need to remove newlines from log. working in it – Rinzwind Nov 19 at 8:08
  • 1
    @Algebra see if this is better :) If not: check JobDeg's answer and accept his is that is the better one for you – Rinzwind Nov 19 at 8:13
6

If the file has newlines, then head and tail can be used to find a specific byte. For a file of ascii characters, chars are equivalent to bytes, but non-ascii unicode characters occupy multiple bytes. Also, the newline characters are counted. To get the byte at position 60000:

$ head -c 60000 file.txt | tail -c -1

To see how this works, the following loop looks at the first 9 bytes:

$ # First the data layout
$ echo $'123\n56\n89'
123
56
89
$ # Now get the first 9 bytes in turn
$ for i in `seq 9`; do c=`echo $'123\n56\n89' | head -c $i | tail -c -1` ; echo "$i => |$c|"; done
1 => |1|
2 => |2|
3 => |3|
4 => ||
5 => |5|
6 => |6|
7 => ||
8 => |8|
9 => |9|

Bytes 4 and 7 are newline characters.

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.