bash 用bash读取文本文件的前8个字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14364397/
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 first 8 characters of text file with bash
提问by user788171
I would like to read only the first 8 characters of a text file and save it to a variable in bash. Is there a way to do this using just bash?
我只想读取文本文件的前 8 个字符并将其保存到 bash 中的变量中。有没有办法只使用 bash 来做到这一点?
回答by gpoo
You can ask head
to read a number of bytes. For your particular case:
您可以要求head
读取多个字节。对于您的特定情况:
$ head -c 8 <file>
Or in a variable:
或者在一个变量中:
foo=$(head -c 8 <file>)
回答by Olivier Dulac
in bash
在 bash
help read
you'll see that you can :
你会发现你可以:
read -r -n 8 variable < .the/file
If you want to read the first 8, independent of the separators,
如果你想阅读前 8 个,独立于分隔符,
IFS= read -r -n 8 variable < .the/file
But avoid using
但避免使用
.... | while IFS= read -r -n 8 variable
as, in bash, the parts after a "|" are run in a subshell: "variable" would only be changed in that subshell, and it's new value lost when returing to the present shell.
因为,在 bash 中,“|”之后的部分 在子shell中运行:“变量”只会在该子shell中更改,并且在返回到当前shell时会丢失新值。
回答by mrkafk
You could use an array in bash and select only first characters. Advanced Bash Scripting guide has good examples how to use arrays.
您可以在 bash 中使用数组并仅选择第一个字符。Advanced Bash Scripting guide 有很好的例子说明如何使用数组。