如何在 bash 中获取一个字符串并将其拆分为 2 个变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8516082/
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
How do I take a string and split it into 2 variables in bash?
提问by waa1990
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 $firstand $last. What is the easiest way to do this?
我有一个从格式为“firstname lastname”的文件中读入的字符串。我想拆分该字符串并将其放入两个单独的变量$first和$last. 什么是最简单的方法来做到这一点?
回答by Fritz G. Mehner
read can do the splitting itself, e.g.
read 可以自己进行拆分,例如
read first last < name.txt
echo "$first"
echo "$last"
回答by l0b0
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) and readto split it. Some examples:
扩展 fgm 的答案,只要您有一个包含由单个字符分隔的标记的字符串,这些标记不属于任何标记,并以换行符终止,您可以使用内部字段分隔符 ( IFS) 并将read其拆分。一些例子:
echo 'John Doe' > name.txt
IFS=' ' read first last < name.txt
echo "$first"
John
echo "$last"
Doe
echo '+12 (0)12-345-678' > number.txt
IFS=' -()' read -a numbers < number.txt
for num in "${numbers[@]}"
do
echo $num
done
+12
0
12
345
678
A typical mistake is to think that read < fileis equivalent to cat file | reador echo 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 once readcompletes. To fix this, you can either do all the operations with the variables in the same subshell:
一个典型的错误是认为它read < file等同于cat file | reador echo contents | read,但事实并非如此:管道中的读取命令在单独的子shell中运行,因此一旦read完成,这些值就会丢失。要解决此问题,您可以在同一个子 shell 中对变量执行所有操作:
echo 'John Doe' | { read first last; echo $first; echo $last; }
John
Doe
or if the text is stored in a variable, you can redirect it:
或者如果文本存储在变量中,您可以重定向它:
name='John Doe'
read first last <<< "$name"
echo $first
John
echo $last
Doe
回答by xvdd
cutcan split strings into parts separated by a chosen character :
cut可以将字符串分成由选定字符分隔的部分:
first=$(echo $str | cut -d " " -f 1)
last=$(echo $str | cut -d " " -f 2)
It is probably not the most elegant way but it is certainly simple.
这可能不是最优雅的方式,但它肯定很简单。
回答by LeleDumbo
$first=`echo $line | sed -e 's/([^ ])+([^ ])+//'`
$last=`echo $line | sed -e 's/([^ ])+([^ ])+//'`

