bash 用分号分隔单词
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8589376/
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
split for words separated with semicolon
提问by Lukap
I have some string like
我有一些像
1;2;3;4;5
1;2;3;4;5
I want to be able to iterate over this string taking each word one by one. For the first iteration to take 1 the next to take 2 and the last 5.
我希望能够一个接一个地遍历这个字符串。第一次迭代取 1,下一次取 2,最后取 5。
I want to have something like this
我想要这样的东西
for i in $(myVar)
do
echo $i
done
but I do not know how to fill the myvar
但我不知道如何填写 myvar
采纳答案by Costi Ciudatu
echo '1;2;3;4;5' | tr \; \n | while read line ; do echo $line; done
回答by l0b0
There's no need to back up the IFS variable if you assign it only for a single command:
如果您只为单个命令分配 IFS 变量,则无需备份:
$ IFS=';' read -a words <<<"1;2;3;4;5"
$ for word in "${words[@]}"
do
echo "$word"
done
1
2
3
4
5
Other useful syntax:
其他有用的语法:
$ echo "${words[0]}"
1
$ echo "${words[@]: -1}"
5
$ echo "${words[@]}"
1 2 3 4 5
回答by pgl
Probably the easiest way to do this is change the IFSenvironment variable:
可能最简单的方法是更改IFS环境变量:
OLDIFS="$IFS"
IFS=';'
for num in $a; do echo $num; done
# prints:
1
2
3
4
5
IFS="$OLDIFS"
Remember to change it back afterwards or weird things will happen! :)
之后记得改回来,不然会发生奇怪的事情!:)
From the bash man page:
从 bash 手册页:
IFS The Internal Field Separator that is used for word splitting
after expansion and to split lines into words with the read
builtin command. The default value is ``<space><tab><new-
line>''.
回答by potong
This might work for you:
这可能对你有用:
array=($(sed 'y/;/ /' <<<"1;2;3;4;5"))
for word in "${array[@]}"; do echo "$word"; done

