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.
Asked
Active
Viewed 1.5k times
4
-
2This 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 Answers
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
-
may not work as you want if one of the first two bytes are in $IFS, dd will do – PW. Jun 15 '09 at 09:31
-
True, but there's no other BASH way to do it, as far as I know. – Vinko Vrsalovic Jun 15 '09 at 09:37
-
1Anyway, as long as you are using a single name, there should be no problems, as $IFS enters the picture when you are splitting the line into more than one name (or variable). – Vinko Vrsalovic Jun 15 '09 at 09:42
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
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.
-
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