使用bash从文本文件中读取字符

时间:2022-04-20 17:07:32

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.

有谁知道如何使用bash脚本从文件中读取前两个字符。有问题的文件实际上是一个I / O驱动程序,它没有新的行字符,并且实际上是无限长的。

4 个解决方案

#1


The read builtin supports the -n parameter:

read builtin支持-n参数:

$ 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;)

#2


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

我认为dd if = your_file ibs = 2 count = 1就可以了

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 :

用strace来看它,它实际上是从文件中读取两个字节。这是从/ dev / zero读取的示例,并通过管道传输到hd以显示零:

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

#3


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

#4


G'day,

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

为什么不使用od来获得你需要的切片?

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.

编辑:当head命令打印到stdout时,你不能使用head。如果前两个字符不可打印,则看不到任何内容。

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

od命令有几个选项可以根据需要格式化字节。

#1


The read builtin supports the -n parameter:

read builtin支持-n参数:

$ 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;)

#2


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

我认为dd if = your_file ibs = 2 count = 1就可以了

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 :

用strace来看它,它实际上是从文件中读取两个字节。这是从/ dev / zero读取的示例,并通过管道传输到hd以显示零:

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

#3


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

#4


G'day,

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

为什么不使用od来获得你需要的切片?

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.

编辑:当head命令打印到stdout时,你不能使用head。如果前两个字符不可打印,则看不到任何内容。

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

od命令有几个选项可以根据需要格式化字节。