Show character at position in a file

I would like to print the character at a given position using only the command line. E.g.:

<command> 5

Would output a if the 5th char of that file was a.

Since I am dealing with big files, ideally this would be able to handle big files.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

If you want the 5th byte, counting from 1:

dd ibs=1 skip=4 count=1


tail -c +5 | head -c 1

Note that tail counts from 1, so given a file containing abcdefg, this prints e.

dd and tail -c are in POSIX. head -c is common, but isn’t in POSIX; it’s in GNU coreutils, BusyBox, FreeBSD and NetBSd and but not in OpenBSD or Solaris.

Solution 2

With sed:

$ echo 12345 | sed 's/.\{4\}\(.\).*/\1/;q'
$ echo 1234ắ | sed 's/.\{4\}\(.\).*/\1/;q'

Note that sed will fail to produce output if you input contain invalid multi-byte characters in current locale. You can use LC_ALL=C if you work with single byte characters only.

With ASCII file, you can also use dd:

$ echo 12345 | dd bs=1 skip=4 count=1 2>/dev/null

Solution 3

Or using (gnu)grep:

grep -zoP '.{4}\K.'   file

(-z was used to deal with \n before the 5th char)

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply