48

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?

user788171
  • 16,753
  • 40
  • 98
  • 125

3 Answers3

72

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>)
gpoo
  • 8,408
  • 3
  • 38
  • 53
7

in bash

help read

you'll see that you can :

read -r -n 8 variable < .the/file

If you want to read the first 8, independent of the separators,

IFS= read -r -n 8 variable < .the/file

But avoid using

.... | while IFS= read -r -n 8 variable

as, in bash, the parts after a "|" are run in a subshell: "variable" would only be changed in that subshell, and it's new value lost when returing to the present shell.

Olivier Dulac
  • 3,695
  • 16
  • 31
0

You could use an array in bash and select only first characters. Advanced Bash Scripting guide has good examples how to use arrays.

LetMeSOThat4U
  • 6,470
  • 10
  • 53
  • 93
  • This is really only half an answer. How would you select just the first 8 characters from the array? – chepner Jan 16 '13 at 18:34
  • 1
    echo ${arrayZ[@]:1:2} # two three It's right there in ABS. Granted, it's somewhat tedious. Alternative is to use loop. BTW solution above using "head" is not using bash builtins only. "head" is an external program. – LetMeSOThat4U Jan 16 '13 at 18:46