1

作为 shell 脚本的新手,我不清楚 bash 中的引用和拆分概念。在下面的片段中:

array1=("france-country":"Italy-country":"singapore-country")
echo ${#array1[@]}

IFS=":-"

for i in ${array1[@]}
do
       echo "$i"
done
unset IFS

使用 IFS :-,我认为结果将是:

france-country
Italy-country
belgium-country

正如我引用的那样(“法国国家”)。我认为它不应该在“-”上分裂。但结果是:

france
country
Italy
country
belgium
country

如果有人能指出我的理解错误,那就太好了。

4

2 回答 2

0

This script shows how to split a colon-separated string into a Bash array.

#!/usr/bin/env bash

words="france-country:Italy-country:singapore-country:Australia-country"

IFS=':' array1=($words)
numwords="${#array1[@]}"

for((i=0; i<numwords; i++));do
    echo "$i: ${array1[i]}"
done

output

0: france-country
1: Italy-country
2: singapore-country
3: Australia-country

Note that in

array1=($words)

we don't put quotes around $words, as that would prevent word splitting.

We don't actually need the quotes in

words="france-country:Italy-country:singapore-country:Australia-country"

but quotes (either single or double) would be needed if there were any spaces in that string. Similarly, the quotes are superfluous in numwords="${#array1[@]}", and many Bash programmers would omit them because we know the result of ${#array1[@]} will never have spaces in it.

It's a Good Idea to always use quotes in Bash unless you're sure you don't want them, eg in the case of array1=($words) above, or when performing tests with the [[ ... ]] syntax.

I suggest you bookmark BashGuide and browse through their FAQ. But the only way to really learn the arcane ways of quoting and splitting in Bash is to to write lots of scripts. :)

You may also find ShellCheck helpful.

于 2014-11-15T12:27:27.193 回答
0

对于您的问题,您可以简单地将字段分隔符更改为:ie ,因为在您的示例中IFS=:,每个国家/地区名称都由:not分隔:-

array1=("france-country":"Italy-country":"singapore-country")
echo ${#array1[@]}

IFS=":"

for i in ${array1[@]}
do
       echo "$i"
done
unset IFS

仅供参考,bash 中的数组元素由 分隔,space因此整个字符串"france-country":"Italy-country":"singapore-country"是数组的单个元素,因此echo ${#array1[@]}将始终为1. 所以在这个例子中我没有看到任何数组的使用。简单的变量就足够了。

于 2014-11-15T10:34:55.787 回答