bash 如何从bash列表中获取第一个字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18486319/
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 to get first string from a bash list?
提问by sorin
I do have a bash list (space separated string) and I just want to extract the first string from it.
我确实有一个 bash 列表(空格分隔的字符串),我只想从中提取第一个字符串。
Example:
例子:
VAR="aaa bbb ccc" -> i need "aaa"
VAR="xxx" -> i need "xxx"
Is there other trick than using a for with break ?
除了使用 for 和 break 之外还有其他技巧吗?
回答by konsolebox
Try this format:
试试这个格式:
echo "${VAR%% *}"
Another way is:
另一种方式是:
read FIRST __ <<< "$VAR"
echo "$FIRST"
回答by Juto
Maybe use cut?
也许使用切割?
echo $VAR | cut --delimiter " " --fields 1 #number after fields is the
#index of pattern you are retrieving
回答by michas
If you want arrays, use arrays. ;)
如果需要数组,请使用数组。;)
VAR=(aaa bbb ccc)
echo ${VAR[0]} # -> aaa
echo ${VAR[1]} # -> bbb
回答by IanM_Matrix1
I'm not sure how standard this is, but this works in Bash 4.1.11
我不确定这是多么标准,但这适用于 Bash 4.1.11
NewVAR=($VAR)
echo $NewVAR
回答by sorin
At this moment the only solution that worked, on both Linux and OS X was:
目前,在 Linux 和 OS X 上唯一有效的解决方案是:
IP="1 2 3"
for IP in $IP:
do
break
done
If you have a better answer, I will be happy to pick it.
如果你有更好的答案,我会很乐意选择它。