This question already has answers here:
How to iterate over text file having multiple-words-per-line using shell script?
                                
                                    (4个答案)
                                
                        
                                3个月前关闭。
            
                    
我有一个像这样的字符串:

Spain-South Africa:2-1


我想像这样拆分它:

Spain-South Africa
2-1


我试图用IFS=':'拆分它,但是它给了我:

Spain-South

Africa
2-1


我的代码:

最佳答案

无法复制,但是您可能没有为IFS命令正确设置read,或者您没有正确显示输出。

$ str="Spain-South Africa:2-1"
$ IFS=: read -ra results <<< "$str"
$ declare -p results
declare -a results=([0]="Spain-South Africa" [1]="2-1")


根据您的短暂评论,您需要

while IFS=: read -ra results; do
    ...
done < "$1"


而不是

for str in $(cat "$1"); do
    ...
done

关于linux - 使用Bash使用IFS分割字符串? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59359700/

10-15 18:17