如何在bash shell中将一个字符串拆分为多个变量? [英] How to split one string into multiple variables in bash shell?
问题描述
我一直在寻找解决方案并发现了类似的问题,只是他们试图用空格分隔句子,而这些答案不适用于我的情况.
I've been looking for a solution and found similar questions, only they were attempting to split sentences with spaces between them, and the answers do not work for my situation.
目前一个变量被设置为这样的字符串:ABCDE-123456
我想把它分成 2 个变量,同时消除-".即:var1=ABCDE
var2=123456
Currently a variable is being set to something a string like this:
ABCDE-123456
and I would like to split that into 2 variables, while eliminating the "-". i.e.:
var1=ABCDE
var2=123456
怎么可能做到这一点?
这是对我有用的解决方案:var1=$(echo $STR | cut -f1 -d-)
var2=$(echo $STR | cut -f2 -d-)
This is the solution that worked for me:
var1=$(echo $STR | cut -f1 -d-)
var2=$(echo $STR | cut -f2 -d-)
是否可以使用 cut 命令而无需分隔符(每个字符都设置为变量)?
Is it possible to use the cut command that will work without a delimiter (each character gets set as a variable)?
var1=$(echo $STR | cut -f1 -d?)
var2=$(echo $STR | cut -f1 -d?)
var3=$(echo $STR | cut -f1 -d?)
等
推荐答案
如果你的解决方案不必是通用的,即只需要像你的例子那样处理字符串,你可以这样做:
If your solution doesn't have to be general, i.e. only needs to work for strings like your example, you could do:
var1=$(echo $STR | cut -f1 -d-)
var2=$(echo $STR | cut -f2 -d-)
我在这里选择 cut
是因为你可以简单地为更多的变量扩展代码......
I chose cut
here because you could simply extend the code for a few more variables...
这篇关于如何在bash shell中将一个字符串拆分为多个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!