read first 8 characters of text file with bash

user788171 picture user788171 · Jan 16, 2013 · Viewed 22.6k times · Source

I would like to read only the first 8 characters of a text file and save it to a variable in bash. Is there a way to do this using just bash?

Answer

gpoo picture gpoo · Jan 16, 2013

You can ask head to read a number of bytes. For your particular case:

$ head -c 8 <file>

Or in a variable:

foo=$(head -c 8 <file>)