简体   繁体   English

重击:将字符串拆分为数组

[英]Bash: Split a string into an array

First of all, let me state that I am very new to Bash scripting. 首先,让我声明我对Bash脚本非常陌生。 I have tried to look for solutions for my problem, but couldn't find any that worked for me. 我试图为我的问题寻找解决方案,但是找不到对我有用的解决方案。
Let's assume I want to use bash to parse a file that looks like the following: 假设我想使用bash来解析如下文件:

variable1 = value1
variable2 = value2

I split the file line by line using the following code: 我使用以下代码逐行拆分文件:

cat /path/to/my.file | while read line; do
    echo $line      
done

From the $line variable I want to create an array that I want to split using = as a delimiter, so that I will be able to get the variable names and values from the array like so: 我想从$line变量中创建一个要使用=分隔的数组,以便可以从数组中获取变量名和值,如下所示:

$array[0] #variable1
$array[1] #value1

What would be the best way to do this? 最好的方法是什么?

Set IFS to '=' in order to split the string on the = sign in your lines, ie: 将IFS设置为'='以便在行中的=号上分割字符串,即:

cat file | while IFS='=' read key value; do
    ${array[0]}="$key"
    ${array[1]}="$value"
done

You may also be able to use the -a argument to specify an array to write into, ie: 您也可以使用-a参数指定要写入的数组,即:

cat file | while IFS='=' read -a array; do
    ...
done

bash version depending. bash版本取决于。

Old completely wrong answer for posterity: 后代的旧完全错误答案:

Add the argument -d = to your read statement. 将参数-d =添加到您的read语句中。 Then you can do: 然后,您可以执行以下操作:

cat file | while read -d = key value; do
    $array[0]="$key"
    $array[1]="$value"
done
while IFS='=' read -r k v; do
   : # do something with $k and $v
done < file

IFS is the 'inner field separator', which tells bash to split the line on an '=' sign. IFS是“内部字段分隔符”,它告诉bash将行分隔为“ =”符号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM