使用 bash 从文本文件中读取字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/974977/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read characters from a text file using bash
提问by Simon Hodgson
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 驱动程序,其中没有换行符,并且实际上是无限长的。
回答by Vinko Vrsalovic
The readbuiltin supports the -nparameter:
将read内置支持-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;)
回答by shodanex
I think
dd if=your_file ibs=2 count=1will 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
回答by Rob Wells
G'day,
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,因为 head 命令打印到标准输出。如果前两个字符不可打印,您将看不到任何内容。
The od command has several options to format the bytes as you want.
od 命令有几个选项可以根据需要格式化字节。
回答by ghostdog74
echo "Two chars" | sed 's/../&\n/g'

