如何在 bash 中获取一个字符串并将其拆分为 2 个变量?
我有一个从格式为“名字姓氏”的文件中读取的字符串。我想拆分该字符串并将其放入两个单独的变量 $first
和 $last
中。做到这一点最简单的方法是什么?
I have a string that is read in from a file in the format "firstname lastname". I want to split that string and put it into two separate variables $first
and $last
. What is the easiest way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
read 可以自行进行分割,例如
read can do the splitting itself, e.g.
扩展 fgm 的答案,只要您有一个包含标记的字符串,由不属于任何标记的单个字符分隔,并且以换行符结尾,您可以使用内部字段分隔符 (
IFS
) 和read
来拆分它。一些例子:一个典型的错误是认为
read << file
相当于cat file |读取
或回显内容| read
,但情况并非如此:管道中的读取命令在单独的子 shell 中运行,因此一旦read
完成,值就会丢失。要解决此问题,您可以使用同一子 shell 中的变量执行所有操作:或者如果文本存储在变量中,则可以重定向它:
Expanding on fgm's answer, whenever you have a string containing tokens separated by single characters which are not part of any of the tokens, and terminated by a newline character, you can use the internal field separator (
IFS
) andread
to split it. Some examples:A typical mistake is to think that
read < file
is equivalent tocat file | read
orecho contents | read
, but this is not the case: The read command in a pipe is run in a separate subshell, so the values are lost onceread
completes. To fix this, you can either do all the operations with the variables in the same subshell:or if the text is stored in a variable, you can redirect it:
cut 可以将字符串分割成由所选字符分隔的部分:
这可能不是最优雅的方式,但它确实很简单。
cut can split strings into parts separated by a chosen character :
It is probably not the most elegant way but it is certainly simple.