4

Does anyone know how I can read the first two characters from a file, using a bash script. The file in question is actually an I/O driver, it has no new line characters in it, and is in effect infinitely long.

Simon Hodgson
  • 563
  • 3
  • 6
  • 12
  • 2
    This is a programming question, but I think you might get a faster response on Serverfault.com. Those guys know their scripting. – C. Ross Jun 10 '09 at 11:22

4 Answers4

11

The read builtin supports the -n parameter:

$ 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;)
fedorqui
  • 275,237
  • 103
  • 548
  • 598
Vinko Vrsalovic
  • 330,807
  • 53
  • 334
  • 373
4

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

Looking at it with strace shows it is effectively doing a two bytes read from the file. Here is an example reading from /dev/zero, and piped into hd to display the zero :

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
shodanex
  • 14,975
  • 11
  • 57
  • 91
  • yes, this one is more robust than read -n for binary (especially for bytes within IFS). V=`dd if=/dev/whatever bs=2 count=1 2>/dev/null` – PW. Jun 15 '09 at 09:35
1
echo "Two chars" | sed 's/../&\n/g'
ghostdog74
  • 327,991
  • 56
  • 259
  • 343
1

G'day,

Why not use od to get the slice that you need?

od --read-bytes=2 my_driver

Edit: You can't use head for this as the head command prints to stdout. If the first two chars are not printable, you don't see anything.

The od command has several options to format the bytes as you want.

unwind
  • 391,730
  • 64
  • 469
  • 606
Rob Wells
  • 36,220
  • 13
  • 81
  • 146
  • These soultions would work on a lot of systems, but I'm using an embedded system that doesn't have head or od installed. – Simon Hodgson Jun 10 '09 at 12:32
  • You don't have head but all the options to read ? My embedded env does the opposite :) And I often put dd in whatever embedded system I build – shodanex Jun 10 '09 at 12:41