Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read first 8 characters of text file with bash

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?

like image 468
user788171 Avatar asked Jan 16 '13 17:01

user788171


People also ask

How do I get the first 10 characters of a file in Unix?

Using the head Command The head command is used to display the first lines of a file. By default, the head command will print only the first 10 lines. The head command ships with the coreutils package, which might be already installed on our machine.

How do you get the first 3 characters of a string in Unix?

To access the first n characters of a string, we can use the (substring) parameter expansion syntax ${str:position:length} in the Bash shell. position: The starting position of a string extraction. length: The number of characters we need to extract from a string.

What does %% mean in Bash?

So as far as I can tell, %% doesn't have any special meaning in a bash function name. It would be just like using XX instead. This is despite the definition of a name in the manpage: name A word consisting only of alphanumeric characters and under- scores, and beginning with an alphabetic character or an under- score.


2 Answers

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>) 
like image 132
gpoo Avatar answered Sep 23 '22 08:09

gpoo


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.

like image 32
Olivier Dulac Avatar answered Sep 19 '22 08:09

Olivier Dulac