Reading characters from a text file using bash

Does anyone know how I can read the first two characters from a file using a bash script. This file is actually an I / O driver, it does not have new line characters in it and is actually infinitely long.

+4
source share
4 answers

The built-in read supports the -n option:

 $ echo "Two chars" | while read -n 2 i; do echo $i; done Tw o ch ar s $ cat /proc/your_driver | (read -n 2 i; echo $i;) 
+10
source

I think dd if=your_file ibs=2 count=1 will do the trick

Looking at this with the strace show, it effectively makes two bytes read from a file. The following is an example of reading from / dev / zero and sent to hd to display a null value:

 dd if=/dev/zero bs=2 count=1 | hd 1+0 enregistrements lus 1+0 enregistrements écrits 2 octets (2 B) copiés, 2,8497e-05 s, 70,2 kB/s 00000000 00 00 |..| 00000002 
+4
source

G'day

Why not use od to get the fragment you need?

 od --read-bytes=2 my_driver 

Edit: You cannot use the head for this, as the head command prints to stdout. If the first two characters cannot be printed, you will not see anything.

The od command has several options for formatting bytes as you want.

+1
source
 echo "Two chars" | sed 's/../&\n/g' 
+1
source

All Articles